Skip to content

Instantly share code, notes, and snippets.

@krohne
Last active February 26, 2018 13:57
Show Gist options
  • Save krohne/18ab7913ab35990e22746b59b25d370e to your computer and use it in GitHub Desktop.
Save krohne/18ab7913ab35990e22746b59b25d370e to your computer and use it in GitHub Desktop.
Multiply by 100 by string manipulation, to avoid floating point problems. Mostly for handling currency.
function x100(nStr) {
function replacer(match, p1, p2) {
return `${`${p1}${p2.padEnd(2, '0').substr(0,2)}`.padStart(1, '0')}.${p2.padEnd(2, '0').substr(2)}`;
}
return String(nStr) // just in case
.replace(/(\d*)\.?(\d*)/, replacer);
}
const tests = [
'0.00',
'0.01',
'0.10',
'1.00',
'1.0',
'1',
'.01',
'.1',
'10.00',
'10.0',
'10.',
'10',
'10.01',
'1.265',
1.265,
'',
'0',
,
'1234567890.1234567890'
];
tests.forEach((element, index) => {
const elementx100 = x100(element);
console.log(`${index+1}: ${element} -> ${elementx100} -> ${Number(elementx100)}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment