-
-
Save Whizboy-Arnold/c5ad7827f1a7b8d870e60be5dbac6f9a to your computer and use it in GitHub Desktop.
Converts a javascript number from scientific notation to a decimal string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment