Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string for only digits and one optional decimal point.

Tags:

c#

numeric

I need to check if a string contains only digits. How could I achieve this in C#?

string s = "123"    → valid 
string s = "123.67" → valid 
string s = "123F"   → invalid 

Is there any function like IsNumeric?

like image 1000
Maneesh Avatar asked Jan 19 '10 09:01

Maneesh


People also ask

What is the regex for decimal number?

A better regex would be /^\d*\.?\ d+$/ which would force a digit after a decimal point. @Chandranshu and it matches an empty string, which your change would also solve.

How do you validate decimals?

To validate decimal numbers in JavaScript, use the match() method. It retrieves the matches when matching a string against a regular expression.

How do you format a string to show two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

double n;
if (Double.TryParse("128337.812738", out n)) {
  // ok
}

works assuming the number doesn't overflow a double

for a huge string, try the regexp:

if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
  // ok
}

add in scientific notation (e/E) or +/- signs if needed...

like image 61
jspcal Avatar answered Oct 06 '22 00:10

jspcal