Possible Duplicate:
JavaScript: formatting number with exactly two decimals
Now that I have got a bit of script to add values in to a div with a total in it, I then try to divide the values by 100 to give me a decimal number (to make it look like currency).
After this the script works and gives me a nice decimal float, sometimes though a large recurring number comes after, I want to limit this to two decimals using the script i already have so was wondering if someone could implement something into my current script.
$(document).ready(function() { $('.add').click(function() { $('#total').text(parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100); }); })
$("#diskamountUnit"). val('$' + $("#disk"). slider("value") * 1.60);
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
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.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
You need to use the .toFixed()
method
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() { $('.add').click(function() { var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100 $('#total').text( value.toFixed(2) ); }); })
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