Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round value to 2 decimals javascript

Tags:

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);

like image 603
Dario Avatar asked Feb 02 '13 21:02

Dario


People also ask

How do I round 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 round decimal value in JavaScript?

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).

How do you round to at most two decimal places if necessary?

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.


2 Answers

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

like image 22
David Avatar answered Oct 03 '22 03:10

David


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. ;)

like image 158
Phrogz Avatar answered Oct 03 '22 04:10

Phrogz