Skip to content
Advertisement

How to convert an integer with n decimal places to a float

I have this integer

7839486009458047182

I have a variable that tells me this number should have n decimal places (In this case 18)

How can I change it to 7.839486009458047182

(If React has this as a method I could use in a template that’s even better!)

Advertisement

Answer

If you’re not too bothered about precision, you can simply divide the integer by 10 ** decimals, for example:

console.log(7839486009458047182 / (10 ** 18));
// ^ 7.839486009458047

Mind that floats have limited precision. If precision is key, keep it as an integer (or bigint). If it’s just for display purposes, then a small amount of imprecision shouldn’t be an issue.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement