Eugene  Zagorulko
Eugene Zagorulko

Reputation: 35

Java number format validation

Can you please advice solution in Java to validate number formats. As input param I receive String. For example, there is Europe format: 1.234,56 Then I do parsing:

NumberFormat.getNumberInstance(locale).parse(value) 

But before parsing I need validation. Example of input data: 1..234,,56 - shouldn't be valid but it parsable

Upvotes: 0

Views: 1765

Answers (2)

Nogard
Nogard

Reputation: 309

Well, there are many possible solutions. But for this situation it would be good to use exceptions. When it is not possible to convert the string into a number, basically write a message to the user that he wrote the wrong number and ask him to enter the new one. For selecting the correct number type, you can use overloading.

try {
    NumberFormat.getNumberInstance(locale).parse(value)
}
catch(Exception e) {
    System.out.println("The number entered is invalid.");
    // Enter the new number code
}

Upvotes: 0

iprashant
iprashant

Reputation: 155

You can go with building your regular expression to check for the format having commas or decimals in a string. Also take reference from the regular expression like : ^\d{1,3}|\d(([ ,]?\d{3})*([.,]\d{2}+)?$)

You can also have a look to this one: Java regex to check if string is valid number format (comma and decimal point placing)

Upvotes: 1

Related Questions