Skip to content

Instantly share code, notes, and snippets.

@jimimaher
Created March 14, 2021 11:48
Show Gist options
  • Save jimimaher/10e4ac629c996d0ca76067bb34459759 to your computer and use it in GitHub Desktop.
Save jimimaher/10e4ac629c996d0ca76067bb34459759 to your computer and use it in GitHub Desktop.
Convert a number to a string without using a one line cast (e.g. number + "")
function floatToString(number) {
function getDecimals(number) {
if (!isFinite(number)) return 0;
let exponent = 1;
let p = 0;
while (Math.round(number * exponent) / exponent !== number) {
exponent *= 10;
p++;
}
return p;
}
const decimals = getDecimals(number);
// also is number length
const decimalIndex = Math.floor(Math.log10(number)) + 1;
let string = '';
let numberTracker = number;
function shiftFirstDigit(i) {
const power = Math.pow(10, i);
const digit = Math.floor(numberTracker / power);
string += digit;
numberTracker = Number((numberTracker - (digit * power)).toFixed(decimals));
}
// add digits to left of decimal
for (let i = decimalIndex - 1; i >= 0; i--) {
shiftFirstDigit(i);
}
if (decimals === 0) {
return string
}
string += "."
// convert to integer
numberTracker = numberTracker * Math.pow(10, decimals)
// add digits to right of decimal
for (let i = decimals - 1; i >= 0; i--) {
shiftFirstDigit(i);
}
return string
}
const result = floatToString(123.45);
console.log({ result })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment