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,
CodePudding user response:
The following snippet should be the answer to your updated question:
const yourNumber=1.234567890123e36, ndigits=3;
// returns two variations of the solution:
function mySigDig(num,dig){
return [ (num/(10**Math.floor(Math.log10(num)))).toPrecision(dig),
num.toPrecision(dig).replace(/e.*/,"")]
}
console.log(mySigDig(23,ndigits));
console.log(mySigDig(2345678,ndigits));
console.log(mySigDig(yourNumber,ndigits));
CodePudding user response:
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.
