2

I have a really strange output result from toString() built in function

Here is my code:

function strangeFunction(num)
{
return num.toString();
}


alert( strangeFunction(121.112*100) ); //output: 12111.199999999999 
alert( strangeFunction(.1*100) );  //output: 10 
alert( strangeFunction(1.33*100) ); //output: 133
alert( strangeFunction(133.33*100) ); //output: 13333.000000000002 
alert( strangeFunction(133.33*100) );//output: 13334 

http://jsfiddle.net/sVMf4/

Any suggestions how to fix that issue? It seems that ther is some kind of bug or number formatting issue.

vorillaz
  • 6,098
  • 2
  • 30
  • 46

4 Answers4

1

It's not JavaScript only, virtually every language manipulating floating point value have this issue.

To avoid it, you can use Math.round() or .toFixed().

Math.round(123.456);
// returns 123

123.4.toFixed(2);
// returns "123.40"

There is also .toPrecision() but it may decide to use scientific notation (like 1.2e+2) which is often not wanted.

Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81
0

You can try this:

function numToStr(var number, var dec) {
    return number.toFixed(dec);
}

var number = 121.112*100;

alert(numToStr(number , 0));  

Output:

12111

toFixed() lets you to convert a number into a string, keeping a specified number of decimals.

SamYan
  • 1,553
  • 1
  • 19
  • 38
0

It seems it's an old javascript issue:

How to deal with floating point number precision in JavaScript?

Another possible solution:

function strangeFunction(num)
{
    num = Math.round(num); 
    return num.toString();
}
Community
  • 1
  • 1
VancleiP
  • 657
  • 4
  • 7
0

Its because of the way floating point numbers are saved internally. You can try this if you are sure about the precision you want.

function strangeFunction(num)
{
    return parseFloat(num.toPrecision(12)).toString();
}