• Status: Solved
• Priority: Medium
• Security: Public
• Views: 323

# validating a format xxx.xxxx

hi guys

I have a requirment where i have a decimal field 'rate'  and rate
can be  in format xxx or xxx.xxxx

for example  rate can be 123 or 123.0000  or 123.3333. These are all valid rates

any idea how i can validate the rate in my java class

String rate = null;
if(rate is not in format xxx or xxx.xxxx)
{

//throw error

}

any idea, how i do this?

thanks
J
0
jaggernat
• 4
• 4
• 2
• +1
3 Solutions

Commented:
You can use this,

Number x = new DecimalFormat("###.###").parse("122.222");
0

Author Commented:
ok,thanks but i dint completely understand

>>>Number x = new DecimalFormat("###.###").parse("122.222");

this is what i have so far

String rate = "";
if (rate != "" && rate.length() > 0)

{
how do i use the above code here (Number x = new DecimalFormat("###.###").parse("122.222");)
}

thanks
0

Commented:

``````String rate = "122.222";
try {
Number x = new DecimalFormat("###.###").parse(rate);
} catch (ParseException ex) {
ex.printStackTrace();
}
``````
0

Commented:
The idea is parse the string using DecimalFormat,

String rate = ...
if(rate != null && rate.length() > 0) {
Number x = new DecimalFormat("###.###").parse(rate);
if(x==null) {
// Parse error, throw the exception.
}
}
0

Commented:
ok, but an exception should be catched anyway. rate could be not parseable and then you have an exception .

Taking Ajay-Singhs answer and expand it with try/catch:

String rate = ...
if(rate != null && rate.length() > 0) {
try {
Number x = new DecimalFormat("###.###").parse(rate);
if(x==null) {
// Parse error, throw the exception.
}
} catch (ParseException ex) {
// Parse error, throw the exception.
}
}
0

Commented:
>>
I have a requirment where i have a decimal field 'rate'  and rate
can be  in format xxx or xxx.xxxx
>>

Try the below:
``````boolean valid = rate.matches("\\d{3}(?:\\.\\d{4})?");
``````
0

Commented:
(My comment takes your comment literally)
0

Author Commented:
thanks all
0

Commented:
You might as well use Double.parseDouble, since those NumberFormat let most things through. Try

3.splat

for instance ;-)
0

Commented:
hello CEHJ

could you please explain this part of the regex?
(?: .... )?

thank you.

manuel
0

Commented:
a. Don't save it
b. Allow one or zero occurences of it

(I assume you know what 'it' is - if not, let me know)
0

Commented:
Yes, I know what 'it' is. Thank you for your response and your explanation!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Featured Post

• 4
• 4
• 2
• +1
Tackle projects and never again get stuck behind a technical roadblock.