I'm working on a web tool which makes some financial calculations and uses multiple numbers in inputs. Is there a way to display that number with only 2 decimals but behind when the app makes the math to use the entire number with all decimals? Something like excel cell which shows 2 decimals but behind the number has 10 decimals.
The problem is that if I round the numbers, the app gives incorrect values. It's just for display purpose to make it look neat and tidy.
Thx.
For ex:
Input real value: 8952340.66543023 Input display value: 8952340.67
You could write a general function which can round to any number of digits :
const roundTo =
num =>
digits =>
Math.round(num * (10 ** digits)) / 10 ** digits
const num = 1234.8304
const roundToTwo = roundTo(num)(2)
console.log(roundToTwo) // logs 1234.83
Where num is your number and digits is the n of digits after the comma.
const f1 = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log("first -> ", f1.format(8952340.66543023));
const f2 = (n, d) => n.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log("Second -> ", f2(8952340.66543023));
Try this code, and tell me.
you can use toFixed(2) to reduce precision to two decimals.
but beware the return value is a string not a number
let float = 1.23456789;
let fixed = float.toFixed(2);
console.log(fixed );
console.log(typeof(fixed))