JavaScriptFundamental (ES6), part 1
Parse a currency string to a number in JavaScript
86 Turning a price string into kobo, and the parsers that lie
fairConvert a price written the way a customer writes it, ₦1,250.50, into an integer number of kobo. Compare Number, parseInt and parseFloat on the same inputs, and show what each one does with junk. Then take Number.isInteger at its word and find out what it actually checks.
Stuck? Three hints, smallest first
- 1.
Numberwants the whole string and givesNaNif anything is left over.parseIntandparseFloatread a prefix and stop. - 2. Strip everything that is not a digit or a dot, then multiply by 100 and round — but check the stripped string first, because
Number('')is0. - 3.
Number.isIntegerasks whether the value has no fractional part. It says nothing about the type of the argument, or about the number being safe.
const naiveKobo = (text) => Math.round(Number(String(text).replace(/[^0-9.]/g, '')) * 100);
const kobo = (text) => {
const cleaned = String(text).replace(/[^0-9.]/g, '');
if (cleaned === '') return null;
const naira = Number(cleaned);
return Number.isFinite(naira) ? Math.round(naira * 100) : null;
};
const wholeOrNothing = [Number.isNaN(Number('12abc')), parseInt('12abc', 10), parseFloat('3.5kg')];
const exponent = [parseInt('1e3', 10), Number('1e3'), parseFloat('1e3')];
const blanks = [Number(''), Number(' '), naiveKobo('free')];
const guarded = [kobo('₦1,250.50'), kobo('free'), kobo(' 200 ')];
const commaStops = parseFloat('1,250.50');
const tinyNumber = parseInt(0.0000005, 10);
const integers = [Number.isInteger(5.0), Number.isInteger(5e20), Number.isInteger('5'), Number.isSafeInteger(2 ** 53)];
const unsafe = [2 ** 53 === 2 ** 53 + 1, Number.MAX_SAFE_INTEGER];
const nanCheck = [isNaN('abc'), Number.isNaN('abc'), Number.isNaN(Number('abc'))];
const separators = [1_000, Number.isNaN(Number('1_000'))];
console.log('whole :', wholeOrNothing, '| exponent:', exponent);
console.log('blanks :', blanks, '| guarded:', guarded);
console.log('comma :', commaStops, '| 0.0000005 ->', tinyNumber);
console.log('isInteger :', integers, '| unsafe:', unsafe);
console.log('NaN :', nanCheck, '| separators:', separators);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('Number demands the whole string; the parsers take a prefix and stop', wholeOrNothing, [true, 12, 3.5]);
test('so parseInt stops dead at the e that Number reads as an exponent', exponent, [1, 1000, 1000]);
test('an empty or blank string is zero, which is how "free" becomes ₦0.00', blanks, [0, 0, 0]);
test('checking the stripped string first turns that into an honest null', guarded, [125050, null, 20000]);
test('parseFloat stops at the comma, and parseInt reads the 5 out of 5e-7', [commaStops, tinyNumber], [1, 5]);
test('isInteger is about the value, not the type, the notation or the safety', integers, [true, true, false, false]);
test('past MAX_SAFE_INTEGER two different integers compare equal', unsafe, [true, 9007199254740991]);
test('the global isNaN coerces first; Number.isNaN never does', nanCheck, [true, false, true]);
test('a numeric separator is a source-code feature, invisible to the parser', separators, [1000, true]);
The three converters disagree on purpose. Number is all-or-nothing: leading and trailing space is fine, one leftover character is NaN. parseInt and parseFloat read as far as they can and return what they got, which is why parseFloat('1,250.50') is 1 and not an error — the worst kind of wrong answer, because it is a plausible number. For money, strip the formatting yourself and use Number, so anything unexpected shows up as NaN instead of a silent truncation.
Number('') being 0 is the bug this exercise is really about. Strip the non-digits out of free and you are left with an empty string, which becomes zero, which becomes a ₦0.00 order that looks deliberate. The one-line guard is to test the cleaned string before converting it. Always pass a radix to parseInt too: parseInt('0x1f') is 31, and the same function handed a small float reads its exponent notation as digits.
Number.isInteger checks the value, and every JavaScript number is a float, so 5.0 is an integer and 5e20 is one as well. It is not a validator: it says false for the string '5', and true for numbers so large that arithmetic on them has stopped being exact — that is what Number.isSafeInteger is for. Kobo as an integer keeps you well inside the safe range and away from 0.1 + 0.2 entirely, which is why money belongs in the smallest unit.