Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate decimals in JavaScript without Math library?

I need numbers to have only 2 decimals (as in money), and I was using this:

Number(parseFloat(Math.trunc(amount_to_truncate * 100) / 100));

But I can no longer support the Math library.

How can I achieve this without the Math library AND withou rounding the decimals?

like image 645
David Prieto Avatar asked Feb 04 '26 07:02

David Prieto


2 Answers

You can use toFixed

Number(amount_to_truncate.toFixed(2))

If you are sure that your input always will be lower or equal than 21474836.47 ((2^31 - 1) / 100) (32bit) then:

if you need as string (to make sure result will have 2 decimals)

((amount_to_truncate * 100|0)/100).toFixed(2)

Otherwise

((amount_to_truncate * 100|0)/100)

Else: See Nina Schols's answer

console.log((((15.555 * 100)|0)/100)) // will not round: 15.55
console.log((((15 * 100)|0)/100).toFixed(2)) // will not round: 15.55
like image 145
Tolgahan Albayrak Avatar answered Feb 05 '26 19:02

Tolgahan Albayrak


Make it simple

const trunc = (n, decimalPlaces) => {
  const decimals = decimalPlaces ? decimalPlaces : 2;
  const asString = n.toString();
  const pos = asString.indexOf('.') != -1 ? asString.indexOf('.') + decimals + 1 : asString.length;
  return parseFloat(n.toString().substring(0, pos));
};

console.log(trunc(3.14159265359));
console.log(trunc(11.1111111));
console.log(trunc(3));
console.log(trunc(11));
console.log(trunc(3.1));
console.log(trunc(11.1));
console.log(trunc(3.14));
console.log(trunc(11.11));
console.log(trunc(3.141));
console.log(trunc(11.111));
like image 30
manonthemat Avatar answered Feb 05 '26 21:02

manonthemat