JSFiddle - React, Tailwind, and code Playground
by Yurii Predborskyi
JavaScript
function round(number, decimals = 0) {
// for (let i = decimals; i > 0; --i) {
// number = Math.round(number * Math.pow(10, i)) / Math.pow(10, i);
// }
// return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
let s = '' + number;
let dot = s.indexOf('.');
let start = dot + decimals + 1;
console.log('dot', dot);
console.log('substring', s.substring(start, start + 1));
console.log('decimals', decimals)
let dec = Number.parseInt(s.substring(start, start + 1));
console.log('dec', dec);
let remainder = dec >= 5 ? 1 / Math.pow(10, decimals) : 0;
console.log('remainder', remainder);
return Number.parseFloat(s.substring(0, dot + decimals)) + remainder;
}
console.log(round(0.145, 2));