Re: decimal place checking using JDK1.3
On Nov 21, 2:56 pm, "timothy ma and constance lee" <timco...@shaw.ca>
wrote:
Dear Sir/Madam
Sir
Thank you for some clue but I am using jdk1.3 so it is not easy to use
regular expression,
Please kindly help
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?
You can use something like the following code as a starting point.
You might like to add additional parameters that accept a
value constraint for the number of digits before and after
the decimal point, or even create these methods in a separate
class altogether - It's up to you to modify it to suit your needs.
I have created some basic test cases, so you can run it to see
the results.
public class CheckNumberFormat
{
public static boolean isParseable( String src ) {
Double.parseDouble( src );
return true;
}
public static boolean isValidFormat( String src ) {
final int NOT_FOUND = -1;
if( !isParseable( src ) || src.indexOf( '.' ) == NOT_FOUND )
return false;
return src.indexOf( '.' ) < 4 &&
src.length() - (src.indexOf( '.' ) + 1) < 8;
}
public static void main( String[] args )
{
String[] numArray = { "123", "123.4567890 ", ".2", "0.1", "0.0",
"1.2", "1234.1", "0.55", "0.12345678", "." };
try
{
for( String token : numArray ) {
if( isValidFormat( token.trim() ) )
System.out.println( "Passed: " + token );
else
System.out.println( "\t\t\tRejected: " + token );
}
}
catch( NumberFormatException e )
{
System.out.println( "Could not parse token: " +
e.getMessage() );
}
}
}
--
Chris