Adding commas to large numbers in d3.js - javascript

I have data points on a line, when the cursor passes over them, a tooltip div appears with data about that point. The code for the html of the div is below.
div.html("The Avengers Box Office: $" + d.Avengers)
d.Avengers returns 207438708 as a string. So is there any way to add commas to large numbers in d3.js?
I have values ranging from thousands to hundreds of millions and it can be tricky to read them.
Thanks

Solution:
You can't add commas using d3 but you can do via plain JavaScript: Number.toLocaleString()
// convert Avengers to a Number and use the toLocaleString on it
div.html("The Avengers Box Office: $" + (1*d.Avengers).toLocaleString() )
Advanced Solution: If your main problem is that numbers are just too big (even with commas), you need write some really cool conversion functions for your numbers that
count the decimals and
choose a really nice format to display nice numbers
Check out a somehow related answer where I added some code to do that, converting big numbers to "kilo", "mega", "giga", and "terra". You might want to adopt that.

Thanks for the replies guys. I found the answer here. Its not adding commas, but its adding M or K after millions or thousands. Which is actually better I think.
https://groups.google.com/forum/?fromgroups=#!topic/d3-js/YFsSmzu4JZk

d3.format(',')(1999222) //// output=1,999,222

Related

Round a number to two digits

I have an issue trying to round some numbers to two digits.
I know it's not that complicated, I'm trying to do it this way:
console.log(parseFloat(3.4155113501943415e-303).toFixed(2))
console.log(parseFloat(8.224160000472033e-304).toFixed(2))
console.log(parseFloat(8.769850182148146e-304).toFixed(2))
But I have an issue with toFixed, it only returns 0.00 for all my numbers.
I suspect that it's due to that fact that my numbers are written this way:
3.4155113501943415e-303
8.224160000472033e-304
8.769850182148146e-304
​etc.
With the e-304 at the end. Is it the issue? Do I have to delete that part or is there any way around it?
I think I saw a problem same as yours Parsing and converting exponential values to decimal in JavaScript. The problem is that 3.4155113501943415e-303 means three hundred zeros in front 0.0000..(and so on up to 300)..00000034155113501943415. So when you use toFixed(2) you get only 0.00. On the link I gave you there is a function which turns exponential number to double and then you can round it.
I just used toPrecision() and it worked. In the example they gave me they just removed the "e-n" which is just lazy in my opinion, we just don't know if it's e-343 or e-342 for example, which is a crazy thing to do.
Anyway, I've found the answer, thank you all!

jquery and JSON how to I format a number as dollars and cents?

I'm my fiddle, http://jsfiddle.net/w2QHz/21/ , my search results show a 'number', but I need them to show as dollars and cents, or at least move the decimal two places as well as display any trailing zero.
I have tried several different mathematical equations, but I found out that my real trouble is displaying the trailing zero. I have been trying toFixed(2), but couldn't figure it out. Where to I put toFixed(2), or is there an easier way to get the results I want?
.append(th.clone().text(value.editions[0].price.high))
"$" + (+value.editions[0].price.high).toFixed(2)
See the documentation for toFixed
.append(th.clone().text("$" + (+value.editions[0].price.high).toFixed(2) ))
Use like this,
parseInt(value.editions[0].price.high).toFixed(2)

Javascript - extract specific numbers from string

I'm trying to extract specific numbers from a string but I'm not sure how to execute it.
The string is of the form:
center=43.571464,7.129565&zoom=12&size=480x225&markers=color:red%7Clabel:1%7C43.580293713725936,7.115145444335894&markers=color:red%7Clabel:2%7C43.56512073056565,7.121668576660113&sensor=false
The array I want is the marker coordinates near the end, specifically:
[43.580293713725936,7.115145444335894,43.56512073056565,7.121668576660113]
I thought I could pick these number out using their precision (15) but I don't know if that's best. I'm a hack when it comes to using regular expressions. Right now the best I've got is:
str.match(/[-+]?[0-9]*\.?[0-9]+/g)
But that just gives me all of the numbers.
Help much appreciated!
If your string is in str use this regex.
var coordinates = decodeURIComponent(str).match(/([\d.]{10,})/g);
http://jsfiddle.net/CHfcT/
You could try using the following regex
/\d+\.\d{7,}/g
This assumes that:
The marker coordinates always have 7 or more numbers after the dot
No other part of the string contains a similar pattern with more than 7 numbers after a dot
Example (JSFiddle):
str.match(/\d+\.\d{7,}/g);
The reason I picked 7 was because the other numbers in the sample had 6, so that excludes them. If you know that the coordinates always have a fixed number of decimal places, then you could just use that specific number without the , like this:
/\s+\.\d{10}/g

Javascript calculation gives too many zero digits

I think it's time get some second opinions on the javascript I'm working on at the moment.
I'm trying to create a calculator to tell people if they can save money by using a subscription etc etc. The calculation itself is done by som inputs from the client and some prevalues from Umbraco CMS.
The result I get from the calculator at the moment is "right" in that the actual numbers are correct, but there's just too many zeroes in it.
The calculator can be found here: my calculator
The test data I'm using is the following:
Antal ansatte: 4
Gennemsnitlig ordreværdi kr. (ca.): 400
Antal ordrer årligt (ca.): 5500
Overskudsgrad (hvad er det?): 2.7
Which gives the output: 712800.0000000001
I tried to divide this by 100 and, of course, it just moved the comma/dot two steps the left. Still there's all those zeroes.
Any help/hint is greatly appreciated! :-)
Thanks in advance,
Bo
P.S. The result I'm looking for would be 7128.00
I believe you want to call toFixed on your integer.
(712800.00000001/100).toFixed(2)
"7128.00"
It will change your number into a string, but if it is for display purposes it should be fine.
You can do something like this:
value.toFixed(2);
This will round off all your trailing decimals to only 2.
You may want to use the round() method like this:
var val = Math.round(val*100)/100
This will give you the 2-decimal place precision you want, with rounding when needed.
Try this:
http://www.mredkj.com/javascript/nfbasic2.html
It is Number Format code for decimal places.
I suspect that you're running into floating point rounding errors (Is floating point math broken?). Try the solutions presented in Is there a definitive solution to javascript floating-point errors?.

Javascript can't render this number correctly: 3494793310847464221

I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function.
Here is some example code to show the error to its fullest.
<html><head><script language="javascript">alert( 3494793310847464221);
var rar = 3494793310847464221;
alert(rar);
</script></head></html>
This has completly baffeled me and for once google is not my friend...
btw the number is 179 more then the number there...
Your number is larger than the maximum allowed integer value in javascript (2^53). This has previously been covered by What is JavaScript's highest integer value that a Number can go to without losing precision?
In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the Wikipedia article for more info), so your number isn't able to be represented exactly.
You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head).
Edit: After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's JavaScript High Precision Calculator.
Use a string instead.
179 more is one way to look at it. Another way is, after the first 16 digits, any further digit is 0. I don't know the details, but it looks like your variable only stores up to 16 digits.
That number exceeds (2^31)-1, and that's the problem; javascript uses 32-bit signed integers (meaning, a range from –2,147,483,648 to 2,147,483,647). Your best choice is to use strings, and create functions to manipulate the strings as numbers.
I wouldn't be all too surprised, if there already was a library that does what you need.
One possible solution is to use a BigInt library such as: http://www.leemon.com/crypto/BigInt.html
This will allow you to store integers of arbitrary precision, but it will not be as fast as standard arithmetic.
Since it's to big to be stored as int, it's converted to float. In JavaScript ther is no explicit integer and float types, there's only universal Number type.
"Can't increment and decrement a string easily..."
Really?
function incr_num(x) {
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=9) return (x.substring(0,x.length-1))+""+(lastdigit+1);
if (x=="9") return "10";
return incr_num(x.substring(0,x.length-1))+"0";
}
function decr_num(x) {
if(x=="0") return "(error: cannot decrement zero)";
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=0) return (x.substring(0,x.length-1))+""+(lastdigit-1);
if (x=="10") return "9"; // delete this line if you like leading zero
return decr_num(x.substring(0,x.length-1))+"9";
}
Just guessing, but perhaps the number is stored as a floating type, and the difference might be because of some rounding error. If that is the case it might work correctly if you use another interpreter (browser, or whatever you are running it in)

Categories