-1

can someone let me know how I can achieve this type of rounding in javascript:

95.123 => 95.13
95.120 => 95.12
95.129 => 95.13
124.121 => 124.13

Thanks for the help.

A

jay4116
  • 57
  • 1
  • 1
  • 9

2 Answers2

1

Use Math.ceil(num * 100) / 100

console.log(Math.ceil(95.123 * 100) / 100);
console.log(Math.ceil(95.120 * 100) / 100);
console.log(Math.ceil(95.129 * 100) / 100);
console.log(Math.ceil(124.121 * 100) / 100);
Karan
  • 12,059
  • 3
  • 24
  • 40
0

A quick and easy way is to multiply by 100, round, and divide by 100.

let value = 95.123;
let rounded = Math.round(value * 100) / 100;

Another option is to use Number.toFixed() (be careful here, as toFixed() returns a string, not a number).

let value = 95.123;
let rounded = Number((value).toFixed(2));

A slightly more fancy approach would be to use exponential notation.

let value = 95.123;
let rounded = Number(Math.round(value+'e2')+'e-2');

This can be refactored into a helper function to handle different decimal values.

function roundToDec(value, decimals) {
  let posExp = 'e' + decimals;
  let negExp = 'e-' + decimals;
  return Number(Math.round(value + posExp) + negExp);
}

let value = 95.123;
let rounded = roundToDec(value, 2);
Hristo
  • 45,559
  • 65
  • 163
  • 230