Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing decimals without rounding up?

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.

like image 281
user3659911 Avatar asked Jan 27 '15 12:01

user3659911


People also ask

How do you get rid of extra decimals in Excel?

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.

How do you remove decimals from a number?

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.


2 Answers

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.

like image 165
Aaron D Avatar answered Sep 20 '22 01:09

Aaron D


var number = parseInt('' + (num * 100)) / 100;
like image 44
awe Avatar answered Sep 20 '22 01:09

awe