简体   繁体   中英

Round number with lots of decimal places in Javascript

I have a number with an extreme amount of decimal places.

1.5583255870000002e+36

I'm struggling to find a good way to round this down to 2 decimal places using JavaScript.

I've tried a few variations using parseFloat() Math.round() and .toFixed() .

Here is an example using .toPrecision() .

App.currentUSDBalance = Number((App.currentBalance * App.maticPrice).toPrecision(2));

The result is 1.6e+36 . I was hoping for something like 1.59 .

Thanks,

You can use Number(yourNumber.toPrecision(ndigits)) .

 const yourNumber=1.234567890123e36, ndigits=3; console.log(Number(yourNumber.toPrecision(ndigits))); console.log(Number(56.7894432.toPrecision(ndigits))); console.log(Number(567894432..toPrecision(ndigits)));

Apologies for the terrible question.

I ended up solving this by converting to string and dropping the e+X .

App.currentUSDBalance = Number((App.currentBalance * App.maticPrice).toPrecision(3)).toString().split('e')[0];

Thanks for the help.

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