string to integer?

29 views
Skip to first unread message

john c

unread,
Oct 25, 2021, 4:00:51 PM10/25/21
to
hi all,

i'm trying to convert a string to an integer. the string is '+7' (43, 55). so i thought Integer fromString: aString would be the answer. not so easy. it fails with an 'Invalid format for Integer' . not sure why it's an invalid format, but be that as it may, what are my options? just for grins, '-7' --> -7 works just fine, so what is it with '+'?

thanks in advance for help,

john

vin...@gmail.com

unread,
Oct 25, 2021, 7:59:05 PM10/25/21
to
Integer class>>#readFrom: only ever checks for the existence of negative sign to signify a negative number, not the positive sign to signify a positive number. I guess a number without a positive sign is always considered a positive number and the presence of the positive sign is seen as an error.

You will have to strip the positive sign (aString reject: [ :each | each = $+ ])

Vince

john c

unread,
Oct 25, 2021, 8:58:18 PM10/25/21
to
thanks vince,

i arrived at that same conclusion and i'm modifying as we speak. with that said, it strikes me that a valid format should be accepted rather than putting on every developer.

sorry, just ranting.

john

john.a...@gmail.com

unread,
Oct 26, 2021, 8:42:35 AM10/26/21
to
Hi John - the comment for Number class>>readFrom: states

"Any numbers in the stream are expected to obey Smalltalk syntax rather than any locale specific formatting, i.e. this is not intended for reading user input."

...so bearing this in mind the error is correct since +7 is not valid Smalltalk syntax.

I thought that the NumberToText class would handle your scenario since it's part of the MVP framework and thus potentially user-facing. However it also uses Number class>>readFrom: and so has the same problem (though it does at least have a #todo comment on the reverse conversion saying "...should use GetNumberFormat() to produce locale specific output").
Reply all
Reply to author
Forward
0 new messages