Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format decimal number to x10 notation using Javascript?

Tags:

javascript

how to format small decimal number to x10 notation ? For example:

0.00298265 --> 2.98265 x 10^-3
9.72157e-9 --> 9.72157 x 10^-9
like image 978
wkwkwk Avatar asked Jul 01 '26 10:07

wkwkwk


1 Answers

You can format the number with toExponential and replace the e:

console.log(0.00298265.toExponential().replace('e', ' x 10^'));
console.log(9.72157e-9.toExponential().replace('e', ' x 10^'));

or with a function:

function format(num) { return num.toExponential().replace('e', ' x 10^'); }
console.log(format(0.00298265));
console.log(format(9.72157e-9));

or with your own prototype function:

Number.prototype.toMyFormat = function() { return this.toExponential().replace('e', ' x 10^'); }
console.log(0.00298265.toMyFormat());
console.log(9.72157e-9.toMyFormat());

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!