Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a value to 2 decimal places within jQuery [duplicate]

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);   }); }) 
like image 999
Mr Dansk Avatar asked Mar 27 '12 00:03

Mr Dansk


People also ask

How do I get 2 decimal places in jQuery?

$("#diskamountUnit"). val('$' + $("#disk"). slider("value") * 1.60);

How do you make a double show with two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you round a double value to 2 decimal places in JavaScript?

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.

How do you keep a float up 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 %.


1 Answers

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) );   }); }) 
like image 116
Gabriele Petrioli Avatar answered Sep 18 '22 15:09

Gabriele Petrioli