Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Last active December 25, 2022 21:03
Show Gist options
  • Save jiggzson/b5f489af9ad931e3d186 to your computer and use it in GitHub Desktop.
Save jiggzson/b5f489af9ad931e3d186 to your computer and use it in GitHub Desktop.
Converts a javascript number from scientific notation to a decimal string
var scientificToDecimal = function (num) {
var nsign = Math.sign(num);
//remove the sign
num = Math.abs(num);
//if the number is in scientific notation remove it
if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
var zero = '0',
parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
e = parts.pop(), //store the exponential part
l = Math.abs(e), //get the number of zeros
sign = e / l,
coeff_array = parts[0].split('.');
if (sign === -1) {
l = l - coeff_array[0].length;
if (l < 0) {
num = coeff_array[0].slice(0, l) + '.' + coeff_array[0].slice(l) + (coeff_array.length === 2 ? coeff_array[1] : '');
}
else {
num = zero + '.' + new Array(l + 1).join(zero) + coeff_array.join('');
}
}
else {
var dec = coeff_array[1];
if (dec)
l = l - dec.length;
if (l < 0) {
num = coeff_array[0] + dec.slice(0, l) + '.' + dec.slice(l);
} else {
num = coeff_array.join('') + new Array(l + 1).join(zero);
}
}
}
return nsign < 0 ? '-'+num : num;
};
var expect = function(value) {
return {
toEqual: function(otherValue) {
if(value !== otherValue) {
console.error(value+' did not yield the correct result!');
}
}
};
};
expect(scientificToDecimal(2.5e25)).toEqual('25000000000000000000000000');
expect(scientificToDecimal(-1.123e-10)).toEqual('-0.0000000001123');
expect(scientificToDecimal(-1e-3)).toEqual('-0.001');
expect(scientificToDecimal(-1.2e-2)).toEqual('-0.012');
expect(scientificToDecimal(12.12)).toEqual(12.12);
expect(scientificToDecimal(141120000000000000)).toEqual(141120000000000000);
expect(scientificToDecimal('0')).toEqual(0);
expect(scientificToDecimal(1.23423534e-12)).toEqual(0.00000000000123423534);
@PaulRBerg
Copy link

PaulRBerg commented Aug 10, 2021

did you find any solution for this?

Yes, check out from-exponential. Also in case you're doing Ethereum development, check out my package evm-bn, which you can use like this:

import { toBn } from "evm-bn";

// 3141500000000000000
const foo: BigNumber = toBn("3.1415");

@zohaibtahir
Copy link

I write the simple to convert the SN to RN checkout this code
https://github.com/zohaibtahir/Math-Calculations/blob/main/Scientific-notation-to-real_number.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment