Rounding error in javascript and possible string workaround

rounding with string subtraction

by Yurii Predborskyi

JavaScript

function round(number, decimals = 0) {
  let s = '' + number;
  let dot = s.indexOf('.');
  let start = dot + decimals + 1;
  let dec = Number.parseInt(s.substring(start, start + 1));
  let remainder = dec >= 5 ? 1 / Math.pow(10, decimals) : 0;
  let result = Number.parseFloat(s.substring(0, start)) + remainder;
  return result.toFixed(decimals);
}

let num = 0.145;
let precision = 2;

console.log('math round', Math.round(num*Math.pow(10, precision))/Math.pow(10, precision));
// 0.145 rounded down to 0.14 - unexpected result
console.log('string round', round(num, precision));
// 0.145 rounded up to 0.15 - expected result