Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created October 11, 2020 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/833553535fbeadc07c996623ca15ea9b to your computer and use it in GitHub Desktop.
Save dfkaye/833553535fbeadc07c996623ca15ea9b to your computer and use it in GitHub Desktop.
JavaScript Numeric Separator test cases
// 11 Oct 2020
// tl;dr
// Numeric separators are parsed on numbers, not on string arguments passed to the Number constructor.
// JSON.stringify({ value: NaN }) returns "{"value":null}".
/* Test it out */
var tests = [
1111222333,
1_111_222_333,
1.111_222_333,
1.1_1_1_2_2_2_3_3_3,
1.111_222_333e7,
1.1_1_1_2_2_2_3_3_3e7,
// The unformatted numeric string works.
"1222333444",
// Formatted strings don't, including coercion.
"1_222_333_444", // null
"1.2_2_2_3_3_3_4_4_4", // null
"1.2_2_2_3_3_3_4_4_4e7", // null
+"1_333_444_555" // null
// These result in parsing errors.
// 1.2__3, // SyntaxError: Only one underscore is allowed as numeric separator
// 1._1_1_1_2_2_2_3_3_3, // SyntaxError: Invalid or unexpected token
// "1._2_2_2_3_3_3_4_4_4" // SyntaxError: Invalid or unexpected token
];
var test = function(value) {
var result;
try { result = Number(value) }
catch (error) { result = error }
return result;
}
var results = tests.map((v, i) => {
console.log(`test ${ i + 1 }:`, v );
return { test: v, result: test(v) };
});
/*
test 1: 1111222333
test 2: 1111222333
test 3: 1.111222333
test 4: 1.111222333
test 5: 11112223.33
test 6: 11112223.33
test 7: 1222333444
test 8: 1_222_333_444
test 9: 1.2_2_2_3_3_3_4_4_4
test 10: 1.2_2_2_3_3_3_4_4_4e7
test 11: NaN
*/
console.log(
"Results:\n",
JSON.stringify(results, null, 2)
);
/*
Results:
[
{
"test": 1111222333,
"result": 1111222333
},
{
"test": 1111222333,
"result": 1111222333
},
{
"test": 1.111222333,
"result": 1.111222333
},
{
"test": 1.111222333,
"result": 1.111222333
},
{
"test": 11112223.33,
"result": 11112223.33
},
{
"test": 11112223.33,
"result": 11112223.33
},
{
"test": "1222333444",
"result": 1222333444
},
{
"test": "1_222_333_444",
"result": null
},
{
"test": "1.2_2_2_3_3_3_4_4_4",
"result": null
},
{
"test": "1.2_2_2_3_3_3_4_4_4e7",
"result": null
},
{
"test": null,
"result": null
}
]
*/
// The last result is curious. `+"1_333_444_555"` is reported as `null` in the stringified JSON.
// What about raw?
console.log( +"1_333_444_555" );
// NaN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment