How do I check for a decimal point when checking a string is a valid number?
What I am thinking is that I use something like the following, but add code to check for the decimal point!
isNumber :: String -> Bool
isNumber xs = all isDigit xs || add extra code here
Where a valid number is defined in EBNF as:
number -> .digit+ | digit+ [ .digit*]
For example, .5, 1.5, 1, 1. are all valid numbers. + signifies one or more occurrences, and * denotes zero or more.
If Number.isNaN returns false, the string is a valid number. We created a reusable function that takes a string and returns a boolean result for whether the string is a valid number or not. We first check if the value passed to the function doesn't have a type of string, in which case we return false straight away.
Check that the string is not an empty string or contains only spaces. Pass the string to the Number.isNaN () method. If Number.isNaN returns false, the string is a valid number. We created a reusable function that takes a string and returns a boolean result for whether the string is a valid number or not.
Interestingly, the actual strings 'True' and 'False' don'tevaluate as numeric. (because there are no String | Boolean allomorphs.) Note: These routines are usable for most cases but won't detect unicode non-digit numeric forms; E.G. vulgar fractions, Roman numerals, circled numbers, etc.
The NumberUtils.isDigits () method checks if a string contains only Unicode digits. If the String contains a leading sign or decimal point the method will return false: String string = "25" ; if (NumberUtils.isDigits (string)) { System.out.println ("String is numeric!"); } else { System.out.println ("String isn't numeric."
A simple approach involves using readMaybe
for converting a string into a number,
import Text.Read
and so for checking whether it is a Double
,
readMaybe "123" :: Maybe Double
Just 123.0
readMaybe "12a3" :: Maybe Double
Nothing
The latter returns Nothing
, the string is not a valid number. In a similar fashion, if we assume it is an Int
,
readMaybe "12.3" :: Maybe Int
Nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With