Skip to content

Instantly share code, notes, and snippets.

@EvanBalster
Created January 14, 2018 18:39
Show Gist options
  • Save EvanBalster/d8c918f1794b8493802f9b52372d6998 to your computer and use it in GitHub Desktop.
Save EvanBalster/d8c918f1794b8493802f9b52372d6998 to your computer and use it in GitHub Desktop.
Reasonable JavaScript Number-to-String
/*
Convert a number to a string, rounding off apparent floating-point error.
Developed by Evan Balster for the TiddlyWikiFormula plugin.
Rules:
- Don't change the integer part.
- Don't change the first significant digit.
- Preserve the exponential part.
- Upon encountering five or more fractional 0s, round them off.
- Upon encountering five or more fractional 9s, round them up.
- Chop off the decimal point if necessary.
Regex captures: (significant part) (error part) (exponential suffix).
*/
function NumberStringSane(n) {
var s = String(n);
var parse = /^(0\.0*[1-9]\d*?|\d*\.\d*?)(0{5}\d*|9{5}\d*)(|e[+-]\d*)$/.exec(s);
if (!parse) return s;
var kept = parse[1], exp = parse[3];
var end = kept.slice(-1);
if (parse[2][0] === '0') return ((end === '.') ? kept.substr(0,kept.length-1) : kept) + exp;
if (end === '.') return (Number(kept.substr(0,kept.length-1))+1) + exp;
return kept.substr(0,kept.length-1) + (Number(end)+1) + exp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment