import assert from 'node:assert/strict';
// Number() parses the whole string, but accepts some surprising inputs.
assert.equal(Number('42'), 42);
assert.equal(Number(' 42\n'), 42); // surrounding whitespace is ignored
assert.equal(Number(''), 0); // empty string is 0, not an error
assert.equal(Number('0x1f'), 31);
assert.ok(Number.isNaN(Number('12px')));
// parseInt stops at the first bad character and ignores the rest.
assert.equal(parseInt('12px', 10), 12);
assert.equal(parseInt('1e3', 10), 1);
assert.equal(parseFloat('3.14abc'), 3.14);
// A strict integer parser: validate the shape, then check the range.
function parseIntStrict(text: string): number {
if (!/^[+-]?\d+$/.test(text)) throw new SyntaxError(`not an integer: ${JSON.stringify(text)}`);
const n = Number(text);
if (!Number.isSafeInteger(n)) throw new RangeError(`out of range: ${text}`);
return n;
}
assert.equal(parseIntStrict('-120'), -120);
assert.throws(() => parseIntStrict(''), SyntaxError);
assert.throws(() => parseIntStrict('12px'), SyntaxError);
assert.throws(() => parseIntStrict('9007199254740993'), RangeError);
// Formatting.
assert.equal((1234.5).toFixed(2), '1234.50');
assert.equal((1.005).toFixed(2), '1.00'); // 1.005 is really 1.00499999...
// A real tie (0.125 is exact in binary): toFixed and Intl round it away from zero
// by default, while Go, Rust and C++ formatting round it to even.
assert.equal((0.125).toFixed(2), '0.13');
const halfEven = new Intl.NumberFormat('en-US', {
maximumFractionDigits: 2,
roundingMode: 'halfEven'
});
assert.equal(halfEven.format(0.125), '0.12');
assert.equal(String(7).padStart(3, '0'), '007');
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
assert.equal(usd.format(1234567.891), '$1,234,567.89');
assert.equal(new Intl.NumberFormat('de-DE').format(1234567.891), '1.234.567,891');
assert.equal((1234567).toLocaleString('en-US'), '1,234,567');
console.log(parseIntStrict('-120'), (1234.5).toFixed(2), usd.format(1234567.891));