Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Last active August 22, 2024 05: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
/**
* Removes the minus sign from the beginning of the string
*
* @param str
* @returns an array with the first item as true if a minus
* was found and the string minus the minus sign.
*/
function stripSign(str) {
// Check if it has a minus sign
let hasMinus = str.charAt(0) === '-';
// Remove it if it does
if (hasMinus || str.charAt(0) === '+') {
str = str.substring(1);
}
return [hasMinus, str];
}
/**
* Converts a string from scientific notation form to decimal form
*
* @param str
* @returns
*/
function scientificToDecimal(str) {
if (/\d+\.?\d*e[\+\-]*\d+/i.test(str)) {
let isNegative, isSmall;
// Remove the sign by slicing the string
[isNegative, str] = stripSign(str);
// Split it into coefficient and exponent
let [c, e] = str.toLowerCase().split('e');
// Split the coefficient into the whole and decimal portion
let [w, d] = c.split('.');
// Provide and empty sting for safety if in the form n(e)n
d = d || '';
// The total length of the string
let length = w.length + d.length;
// The total string minus the dot
let numString = w + d;
// If it's small then we need to calculate the leading zeros
// The shift of the decimal place to the left
const dotLocation = w.length + Number(e);
// Is the dot needed or not
const dot = dotLocation === length ? '' : '.';
let value;
if (dotLocation <= 0) {
// Join the value but pad after the dot with zeroes
value = `0${dot}${'0'.repeat(Math.abs(dotLocation))}${numString}`;
}
else if (dotLocation > length) {
value = `${numString}${'0'.repeat(Math.abs(dotLocation - length))}`;
}
else {
value = `${numString.substring(0, dotLocation)}${dot}${numString.substring(dotLocation)}`;
}
return isNegative ? '-' + value : value;
}
return str;
}
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);
@zohaibtahir
Copy link

@jiggzson
Copy link
Author

jiggzson commented Aug 6, 2024

Updated.

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