For example, I have a number 123.429
. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42
.
Definitely toFixed()
method or Math.round(num * 100) / 100
cannot be used in this situation.
By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.
To remove the decimal point we have to convert it into a rational number. To convert a decimal to a rational number follow these steps: Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point.
The function you want is Math.floor(x)
to remove decimals without rounding up (so floor(4.9) = 4
).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc()
function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor()
:
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt()
method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
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