I am interacting with an API and it returns the price as in integer, for example:
99.59 is returned from the API like this: 9959
60.00 is returned like this 6000
252.90 is returned like this 25290
I'd love a function that takes in the integer number and turns it to float exactly like the above, so 25290 should be 252.90 and 9959 should be 99.59
Any help Is really appreciated.
CodePudding user response:
You can use something like this.
const formatNumber = (value, precision = 2) => {
return (value / 100).toFixed(precision);
}
console.log(formatNumber(60000, 3));
console.log(formatNumber(2529));
And use that formatNumber
function for formatting.
Like, formatNumber(6000, 3)
and it will return something like 60.000
.
CodePudding user response:
You could take a function and convert the value to a sting, maintain the length and add a dot.
const
format = integer => integer
.toString()
.padStart(3, 0)
.replace(/(?=..$)/, '.');
console.log(format(0));
console.log(format(9));
console.log(format(19));
console.log(format(9959));