How to Check If an Entered Value Is Currency

How can I check if a string follows the pattern of american currency?

Usually, you would use a regular expression for something like this.
A simple regex for this would be ^\$\d+.\d\d$. Basically, it means the string should start with a $ sign, have at last one digit, a dot, and two more digits.

However, this can be done without regular expressions, and since it seems like a homework task, I'll give you a nudge in the right direction.

So you need to test the string starts with $, the char 3rd from the right is a ., and everything else are digits.

Your method should return a bool indicating valid / invalid results - so you should do something like this:

 static bool IsCurrency(string currency)
{

// Check if the string is not null or empty - if not, return false

// check if the string is at least 5 chars long, since you need at least $x.xx - if not, return false

// Check if the first char is $ - if not, return false

// Check if the 3rd char from the end is . - if not, return false

// check if all the other chars are digits - if not, return false

// If all checks are valid -
return true;
}

Note that the order of the tests is critical, for instance if you check the 3rd digit from the right is a . before you check you have at least 5 digits, you might attempt to check a string that is only 2 digits long and get an exception.

Since this is (probably) homework I'm going to leave the code-writing part for you, so you would actually learn something from this.

How to detect if string is currency in c#

If you just do the conversion (you should add | NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint
as well) then if the string contains the wrong currency symbol for the current UI the parse will fail - in this case by raising an exception. It it contains no currency symbol the parse will still work.

You can therefore use TryParse to allow for this and test for failure.

If your input can be any currency you can use this version of TryParse that takes a IFormatProvider as argument with which you can specify the culture-specific parsing information about the string. So if the parse fails for the default UI culture you can loop round each of your supported cultures trying again. When you find the one that works you've got both your number and the type of currency it is (Zloty, US Dollar, Euro, Rouble etc.)

How to validate currency value using JavaScript?

a regex can validate that for you:

/[\$£¥]\d+(\.\d\d)?/

(but with the euro sign in there too)

this one I've given won't be the most robust way to do it. You could alter to your preference. An alternative is to try something like this:

var myString = "$55.32",
currency = parseFloat(myString.replace(/^[^\d\.]*/, ''))
valid = !isNaN(currency)
;

It strips away any non-number or . characters from the start and then parses it as a float.



Related Topics



Leave a reply



Submit