Skip to content

Instantly share code, notes, and snippets.

@tigerhawkvok
Created May 11, 2017 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tigerhawkvok/84fde591a29b31818c5a25baa98ad6e1 to your computer and use it in GitHub Desktop.
Save tigerhawkvok/84fde591a29b31818c5a25baa98ad6e1 to your computer and use it in GitHub Desktop.
Remove exponents from a number in scientific notation, and return "normal" values
String::noExponents = (explicitNum = true) ->
###
# Remove scientific notation from a number
#
# After
# http://stackoverflow.com/a/18719988/1877527
###
data = @.split /[eE]/
if data.length is 1
return data[0]
# Initialize
z = ""
sign = if @.slice(0,1) is "-" then "-" else ""
str = data[0].replace ".", ""
mag = Number(data[1]) + 1
# Deal with negative exponents
if mag <= 0
z = sign + "0."
# Add zeros until we hit mag = 0
until mag >= 0
z += "0"
++mag
# Append all the trailing digits
num = z + str.replace /^\-/, ""
if explicitNum
return parseFloat num
else
return num
# Positive exponents
if str.length <= mag
# There will be no trailing decimals
mag -= str.length
# Loop until we hit zero
until mag <= 0
z += 0
--mag
num = str + z
if explicitNum
return parseFloat num
else
return num
else
# Need to handle the trailing decimal case
leader = parseFloat data[0]
multiplier = 10 ** parseInt data[1]
return leader * multiplier
Number::noExponents = ->
strVal = String @
strVal.noExponents(true)
String.prototype.noExponents = function(explicitNum) {
var data, leader, mag, multiplier, num, sign, str, z;
if (explicitNum == null) {
explicitNum = true;
}
/*
* Remove scientific notation from a number
*
* After
* http://stackoverflow.com/a/18719988/1877527
*/
data = this.split(/[eE]/);
if (data.length === 1) {
return data[0];
}
z = "";
sign = this.slice(0, 1) === "-" ? "-" : "";
str = data[0].replace(".", "");
mag = Number(data[1]) + 1;
if (mag <= 0) {
z = sign + "0.";
while (!(mag >= 0)) {
z += "0";
++mag;
}
num = z + str.replace(/^\-/, "");
if (explicitNum) {
return parseFloat(num);
} else {
return num;
}
}
if (str.length <= mag) {
mag -= str.length;
while (!(mag <= 0)) {
z += 0;
--mag;
}
num = str + z;
if (explicitNum) {
return parseFloat(num);
} else {
return num;
}
} else {
leader = parseFloat(data[0]);
multiplier = Math.pow(10, parseInt(data[1]));
return leader * multiplier;
}
};
Number.prototype.noExponents = function() {
var strVal;
strVal = String(this);
return strVal.noExponents(true);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment