Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  3] [ 4]  / answers: 1 / hits: 184406  / 15 Years ago, wed, february 17, 2010, 12:00:00

Am I missing something here?



var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string


Why does .toFixed() return a string?



I want to round the number to 2 decimal digits.


More From » types

 Answers
248

It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.



For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)



Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.


[#97546] Sunday, February 14, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rebekahalysah

Total Points: 304
Total Questions: 96
Total Answers: 102

Location: Taiwan
Member since Mon, May 2, 2022
2 Years ago
;