Closed boogie closed 1 year ago
Hi. Yes, you're right. The code path for coercing a string to a number is currently not implemented. You're the first person to ask for this functionality. I'll leave this ticket open to track progress on it.
In the meantime, as you say, you can implement a method like parseInt in C and import it.
Ok, Microvium now supports the unary +
operator for converting strings to 32-bit integers (but not general floating point numbers). This is in main
in the repository but has not yet been released to npm.
Note:
0 + str
coerces the 0
to a string rather than coercing str
to a number, as per the spec.Number(str)
and parseInt
are not supported out of the box.Does your use case require parsing of floats as well at this time? Otherwise I'll wait for someone else to require that before implementing it.
And another question: are you using microvium
off npm or are you using it from source from GitHub?
P.S. these are the test cases and show what cases are covered:
assert(Number.isNaN(+"x"));
assert(Number.isNaN(+"length"));
assert(Number.isNaN(+"__proto__"));
assert(Number.isNaN(+"1a"));
assert(Number.isNaN(+"1.1.1"));
assert(Number.isNaN(+"123456789123456789.1.1"));
assert(Number.isNaN(+"123\0"));
// Empty string
assertEqual(+"", 0);
// Whitespace
assertEqual(+" ", 0);
// Small integers
assertEqual(+"123", 123);
assertEqual(+"-123", -123);
// Leading and trailing whitespace
assertEqual(+" 123 ", 123);
assertEqual(+" -123 ", -123);
// Int32
assertEqual(+"12345678", 12345678);
assertEqual(+"-12345678", -12345678);
// Multiply
assertEqual(1 * "123", 123);
Thanks for adding the support. I don't need floats now. I'm using both npm and source code. I've a JS => bytecode server with npm, and just added microvium C sources to my firmware code by downloading the source.
Probably it is trivial, but I've found no documentation about it. If I have a string value, how can I convert it to number?
I would say these are bugs, in normal JavaScript adding a string to a number should end up in a number. These seems to be not working, and I think there's no parseInt method as well (however it's possible to implement).