Let say i have a number
const number = 122.333444555666
i want to write a function that will return the exact decimal's number that i want. For example
formatFunction(number, 5) return 122.33344
formatFunction(number, 7) return 122.3334445
formatFunction(number, 12) return 122.333444555666
formatFunction(number, 15) return 122.333444555666000
formatFunction(number, 20) return 122.33344455566600000000
I tried with toFixed() but i end up with some exception . For ex
12.111222333.toFixed(18) return '12.111222333000000617'
I also try Intl but it always rouned up. Any idea?
When working with floats I like to split at the decimal place and treat both sides as whole numbers. It makes operating on them a bit easier and increases accuracy.
const [wholeNumber, decimals] = num.split(".");
Isolating decimals as a string allows us to quickly compare it to they desired scale, enabling us to determine whether to add or subtract.
if (decimals.length < scale) {
const diff = scale - decimals.length;
const trailingZeros = new Array(diff).fill(0).join("");
decimals += trailingZeros;
}
In the above example we have less decimal places than the desired scale. So we'll create a string of zeros based on the difference to match the scale, then append it to the end of the decimal string.
if (decimals.length > scale) {
decimals = decimals.substr(0, scale);
}
When the decimals places are greater, we can use substr() to cut up to the desired scale.
return join(wholeNumber, decimals)
Lastly we want to rejoin our two sets of numbers using the helper. Note that to satisfy the trailing zeros the answer is returned as a string. Converting it to a number would omit them.
function formatFunction(number, scale) {
// if it's a number need to convert to string
const num = typeof number === 'number' ? number.toString() : number;
let [wholeNumber, decimals] = num.split(".");
if (decimals.length < scale) {
const diff = scale - decimals.length;
const trailingZeros = new Array(diff).fill(0).join("");
decimals += trailingZeros;
} else if (decimals.length > scale) {
decimals = decimals.substr(0, scale);
}
// decimals.length === scale
return join(wholeNumber, decimals)
}
// helper
function join(wholeNumber, decimals) {
if (!decimals) return wholeNumber;
return [wholeNumber, decimals].join(".")
}
const number = 122.333444555666;
console.log(formatFunction(number, 5)) // return 122.33344
console.log(formatFunction(number, 7)) // return 122.3334445
console.log(formatFunction(number, 12)) // return 122.333444555666
console.log(formatFunction(number, 15)) // return 122.333444555666000
console.log(formatFunction(number, 20)) // return 122.33344455566600000000