0

I can't seem to get a nice number rounded to the nearest hundredth (ie. 12.57 instead of 12.57000000008).

var example = {
    user : "John",
    dollars: 12.57
};

setInterval( function() {
    example.dollars += (parseInt(Math.floor(Math.random()*2000 + 500)) / 100);
    console.log(example.dollars);
}, 1000);

I keep getting values like:
15.20000000008
88.54000000007
86.36000000008

Am I setting something wrong in my Math function?

Note: This is in node.js

Justin Elkow
  • 2,833
  • 6
  • 28
  • 60
  • 1
    http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html What Every Computer Scientist Should Know About Floating-Point Arithmetic – Patashu May 11 '13 at 00:39

3 Answers3

2

Javascript numbers are floating point numbers. They should not be relied upon for precision decimal operations.

For instance you can enter this into a js console

.1 + .2 //0.30000000000000004

Generally you can count on integer mathematics accurately,and if you need more control on decimal accuracy, you can look into libraries like this one which lets you set error bounds on your numbers, or make a call to an external library written in a language with better handling of number types.

More libraries for accurate JS decimal math:

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
1

Try isolating the number to the hundredth place. ie [86.36]000000008

var example = {
    user : "John",
    dollars: 12.57
};

setInterval(function() {
    var s, final;
    example.dollars += (parseInt(Math.floor(Math.random() * 2000 + 500)) / 100);

    s = example.dollars + .005 + '',
    final = s.substring(0, s.indexOf('.') + 3); 
    console.log(final);
}, 1000);

All we are doing is removing everything after the hundredth decimal place. in order to do that we need to find the decimal place so we can find the hundredth decimal value per say. First we must convert the number into a string, + '' or you can use the toString() function. then we use indexOf('.') to find the decimal placement and finally we count three places over. that will get you the number to the hundredth place, without the long decimal values.

Examples:
input: 12.57000000008 output: 12.57
input: 15.20000000008 output: 15.20

Working fiddle.

Jay Harris
  • 4,201
  • 17
  • 21
1

If you only need to support modern browsers, the toFixed method is the best choice. It takes an argument representing the number of decimal places to round to and returns a String.

example.dollars.toFixed(2); // returns "12.57"
LandonSchropp
  • 10,084
  • 22
  • 86
  • 149