21

I have a small issue with the final value, i need to round to 2 decimals.

var pri='#price'+$(this).attr('id').substr(len-2);
            $.get("sale/price?output=json", { code: v },
               function(data){
                 $(pri).val(Math.round((data / 1.19),2));
            });
        });

Any help is appreciated.

Solution: $(pri).val(Math.round((data / 1.19 * 100 )) / 100);

Dario
  • 245
  • 1
  • 2
  • 7

2 Answers2

77

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • 2
    `toFixed(2)` rounds 1.025 to 1.02. That is not correct. If you use 1.026 it rounds correctly but not with 5 thus this rounding is wrong. – MrSmith Aug 05 '16 at 09:38
  • @MrSmith That's because it is not actually, exactly `1.025`. `(1.025).toFixed(20)` gives `"1.02499999999999991118"`, which is the closest JavaScript (and any language using [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point numbers) can come to representing your desired `1.025`. Read more [here](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) and [here](http://floating-point-gui.de/) and [here](http://floating-point-gui.de/formats/fp/) and ... – Phrogz Aug 05 '16 at 15:27
14

Just multiply the number by 100, round, and divide the resulting number by 100.

David
  • 877
  • 1
  • 7
  • 18