JSFiddle - React, Tailwind, and code Playground

by Yurii Predborskyi

JavaScript

function round(number, decimals = 0) {
  let strNum = '' + number;
  let negCoef = number < 0 ? -1 : 1;
  let dotIndex = strNum.indexOf('.');
  let start = dotIndex + decimals + 1;
  let dec = Number.parseInt(strNum.substring(start, start + 1));
  let remainder = dec >= 5 ? 1 / Math.pow(10, decimals) : 0;
  let result = Number.parseFloat(strNum.substring(0, start)) + remainder * negCoef;
  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
console.log('toPrecision', num.toPrecision(precision));