Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the amount of number shown after a decimal place in javascript

Hay, i have some floats like these

4.3455 2.768 3.67 

and i want to display them like this

4.34 2.76 3.67 

I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.

like image 953
dotty Avatar asked Nov 23 '10 12:11

dotty


People also ask

How do you limit the numbers after a decimal point?

Using Math.round() method is another method to limit the decimal places in Java. If we want to round a number to 1 decimal place, then we multiply and divide the input number by 10.0 in the round() method. Similarly, for 2 decimal places, we can use 100.0, for 3 decimal places, we can use 1000.0, and so on.

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 limit decimal places to 2?

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.

What is the use of toFixed 2 in JavaScript?

The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.


2 Answers

You're looking for toFixed:

var x = 4.3455; alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted! 

...but it looks like you want to truncate rather than rounding, so:

var x = 4.3455; x = Math.floor(x * 100) / 100; alert(x.toFixed(2)); // alerts 4.34 
like image 187
T.J. Crowder Avatar answered Sep 18 '22 21:09

T.J. Crowder


As T.J answered, the toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

(4.55555).toFixed(2); //-> "4.56"  (4).toFixed(2); //-> "4.00" 

If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

+parseFloat((4.55555).toFixed(2)); //-> 4.56  +parseFloat((4).toFixed(2)); //-> 4 
like image 25
C. J. Avatar answered Sep 20 '22 21:09

C. J.