简体   繁体   中英

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!)

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.

You can divide the integer by 10 raised to the number of decimal places.

 let integer = 7839486009458047182 function setDP(number, decimalPlaces) { return number / 10 ** decimalPlaces } console.log(setDP(integer, 18))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM