This question already has an answer here:
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
This question already has an answer here:
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
To get the result with two decimals, you can do like this :
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Add .toFixed(2) to get the two decimal places you wanted.
You could make a function that will handle the rounding for you:
Example: https://jsfiddle.net/k5tpq3pd/36/
Alternativ
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
and use it like this:
Example https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
The best and simple solution I found is
Reference: http://www.jacklmoore.com/notes/rounding-in-javascript/