Pharo /
TextToNumbersIf you are using a GUI, you will quickly find that all the fields you type into are text fields. But if your code requires a numeric value, you can't just send it a string. Here's a way to validate text as convertible into a number (an integer or float). It is not 100% foolproof (it needs more testing), but it works for the basic 'bad entries':
Here is an example, taken from MyGUI>>setHeaterAdjustment heaterAdjustmentNumber := [heaterAdjustment getText asNumber.] on: Error do: [Transcript cr; show: 'Invalid entry. '. self setMyViewer: String crlf, '**Invalid entry. Numbers only. Floats require a 0 before the decimal'. ^nil]. The block in the first line '[heaterAdjustment getText asNumber.]' tries to convert the text inputted into a number. If asNumber fails, it throws an exception. That exception is caught, and a message is sent to the user. It's a guess what the real reason for the error is, so both are given. Other reasons for rejecting the otherwise valid entry are done separately. For example, if the value should be > 0: (myControl setHeaterAdjustment: heaterAdjustmentNumber) ifTrue: [self setMyViewer: String crlf, '**heaterAdjustment is set to: ', myControl heaterAdjustment asString.] ifFalse: [self setMyViewer: String crlf, '**heaterAdjustment is unchanged. Must be > 0'.] In this case the requirement of the value being > 0 is handled elsewhere (in MyControl>>setHeaterAdjustment). All we see here is the message input to the user, depending on success or failure. In MyControl>>setHeaterAdjustment:aNumber, there's this conditional statement: setHeaterAdjustment: aNumber "change the effect of the heater. Must be a positive number. Should be small like 0.2" "return value true/false is used by MyGUI>>setHeaterAdjustment:" aNumber >= 0 ifTrue: [self heaterAdjustment: aNumber. Transcript cr; show: '**heater factor has been set to: ', aNumber asString. ^true] ifFalse: [Transcript cr; show: '**Not changed. Heater adjustment must be a positive number**'. ^false.]. |