Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: check if string is valid number

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.

like image 869
Zast Avatar asked May 04 '15 11:05

Zast


People also ask

How do you check if a string is a valid number?

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.

How to check if a string is a number in JavaScript?

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.

Are there any strings that don't evaluate as numeric?

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.

How do I check if a string contains only unicode digits?

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."


1 Answers

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
like image 195
elm Avatar answered Sep 17 '22 05:09

elm