0

I would like to trim a number into 3 decimal places then round it in 2 decimal places.

For example:

1.234567

Trim it to 1.234

Then round it = 1.23

Another example:

1.389999

Trim it to 1.389

Then round it: 1.39

I tried using toFixed() function but it automatically round it.

Thanks in advance.

Tester
  • 11

2 Answers2

0

Use the Math.floor method to trim it, then the Math.round method to round it:

var n = 1.23456;
n = Math.round(Math.floor(n * 1000) / 10) / 100;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can multiply the number by a power of 10, use the appropriate math methods, and divide by the same factor.

For rounding, there is Math.round:

function myRound(num, decimals) {
    var factor = Math.pow(10, decimals);
    return Math.round(num * factor) / factor;
}

For truncating, ECMAScript 6 introduces Math.trunc. For old browsers it can be polyfilled or, assuming the number will be positive, you can use Math.floor.

function myTruncate(num, decimals) {
    var factor = Math.pow(10, decimals);
    return Math.trunc(num * factor) / factor;
}

Use them like

myTruncate(1.234567, 3); // 1.234
myTruncate(1.389999, 3); // 1.389
myRound(1.234567, 2); // 1.23
myRound(1.389999, 2); // 1.39
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • The `Math.trunc` method is experimental, not supported in all browsers. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc – Guffa Apr 19 '15 at 21:07