0

I have javascript function that let round to precision any numeric values

Usually it works well. But there are some values returns not very correct result. So what I mean

function roundToPrecision(x, precision) {
  var y = +x + (precision === undefined ? 0.5 : precision / 2);
  return y - (y % (precision === undefined ? 1 : +precision));
}


function test() {
  console.log(roundToPrecision(678.03423424554234, 0.01)) //678.03 OK
  console.log(roundToPrecision(4.12342545544545, 0.01)) //4.12 OK
  console.log(roundToPrecision(34.0516356456356, 0.01)) //34.05 OK
  console.log(roundToPrecision(23.0769230769231, 0.01)) //23.080000000000002 not correct!
  console.log(roundToPrecision(4.06153846153846, 0.01)) //4.0600000000000005 not correct!

}
test()

I don't understand why it is happening. Source values comes from Google Sheet. I know I can use toFixed() but this method returns string. I need numeric results. Where I'm wrong and how to fix it?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Timogavk
  • 809
  • 1
  • 7
  • 20

1 Answers1

1

function roundToPrecision(x, precision) {
  return Number(x.toFixed(precision));
}


function test() {
  console.log(roundToPrecision(678.03423424554234, 2)) //678.03 OK
  console.log(roundToPrecision(4.12342545544545, 2)) //4.12 OK
  console.log(roundToPrecision(34.0516356456356, 2)) //34.05 OK
  console.log(roundToPrecision(23.0769230769231, 2)) //23.080000000000002 not correct!
  console.log(roundToPrecision(4.06153846153846, 2)) //4.0600000000000005 not correct!

}
test()
Chase
  • 3,028
  • 14
  • 15