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);
Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.
The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
Just multiply the number by 100, round, and divide the resulting number by 100.
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:
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"
.
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With