Dear Sir/Madam
Sir
I am trying to write a program which check the format:
123.4567899 which is allowed.
The max no. of digit for integer part is 3 and the max of digit after the
decimal is 7 so total max length is 11.
It is very strange that when enter 0.45 in the result, it is positive.
But it is exception when enter 0.55 - 0.58
public static void main(String[] args) {
Double result = null;
//can try from 0.55 - 0.58 wont work
result = Double.valueOf((String)"0.55");
double netResult = 0.00;
double netResult1 = 0.00;
int decimal = 7;
netResult = result.doubleValue() * Math.pow(10,decimal+1);
netResult1 = netResult % 1;
if (netResult1 >0){
System.out.print("Exception");
}
else{
System.out.print("OK");
}
System.out.print("\nResult = "+result);
System.out.print("\nResult.doubleValue =
"+result.doubleValue());
System.out.print("\nnet Result = "+netResult);
System.out.print("\nnet Result1 = "+netResult1);
}
It is all OK for value except from 0.55 to 0.58 which throw exception,
Any clue?
Please kindly help
Arne Vajhøj - 21 Nov 2007 03:37 GMT
> I am trying to write a program which check the format:
>
> 123.4567899 which is allowed.
>
> The max no. of digit for integer part is 3 and the max of digit after the
> decimal is 7 so total max length is 11.
Maybe regex and Java String "\\d{1,3}\\.\\d{1,7}" ?
Arne
timothy ma and constance lee - 21 Nov 2007 03:50 GMT
Arne
Can you show me the exact code?
thanks
>> I am trying to write a program which check the format:
>>
[quoted text clipped - 6 lines]
>
> Arne
Arne Vajhøj - 21 Nov 2007 04:00 GMT
> Can you show me the exact code?
private static Pattern p = Pattern.compile("\\d{1,3}\\.\\d{1,7}");
public static boolean is37digit(String s)
{
return p.matcher(s).matches();
}
You did not specify minimum of digits, so I guessed at 1.
Arne
Patricia Shanahan - 21 Nov 2007 03:43 GMT
> Dear Sir/Madam
>
[quoted text clipped - 9 lines]
> It is very strange that when enter 0.45 in the result, it is positive.
> But it is exception when enter 0.55 - 0.58
I suspect there will be other cases that fail. The problem is that many
numbers, such as 0.55, that meet your format requirements cannot be
exactly represented as double. The result of the Double.valueOf call is
the closest number that is representable as double, not the exact input.
I would do this either as a String test, or look at BigDecimal.
Patricia