user3659911
user3659911

Reputation: 197

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.

Upvotes: 12

Views: 21302

Answers (7)

Aaron Bostick
Aaron Bostick

Reputation: 1

Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.

Upvotes: 0

Edwin Thomas
Edwin Thomas

Reputation: 1186

Try this

number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);

return parseFloat(number);

Upvotes: 0

Shaheer Wasti
Shaheer Wasti

Reputation: 101

another v. cool solution is by using | operator

let num = 123.429 | 0

let num = 123.429 | 0

console.log(num);

Upvotes: 3

Sanka Weerathunga
Sanka Weerathunga

Reputation: 11

let's get the variable name as "num"

var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;

value of the num variable will be 12.42

Upvotes: 0

Aaron D
Aaron D

Reputation: 7700

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.

Upvotes: 16

Alnitak
Alnitak

Reputation: 339786

You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:

var s = String(123.429);
s.substring(0, s.indexOf('.') + 3);  //   "123.42"

Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.

Upvotes: 1

awe
awe

Reputation: 22442

var number = parseInt('' + (num * 100)) / 100;

Upvotes: 9

Related Questions