Hi!
I'm currently writing a BMI calculator and I have problems with the
DecimalFormat.
//if calculate is pressed
if(c.equals("b"))
{
//check if values are entered
if( weight.getText().length() <1 &&
height.getText().length() <1 )
{
JOptionPane.showMessageDialog(this,
"<html>" +
"<h3>You didn't entered any values!</h3>" +
"<h4>Please enter the values in the specific
fields!</h4>" +
"</html>",
"No data prompted!",
JOptionPane.ERROR_MESSAGE,
null);
} else
{
//are the values in the right format?
try
{
//double must be used or otherwise a comma won't work
//get the content of the TextFields
BMI = calculateBMI( Double.parseDouble(
weight.getText() ),
Double.parseDouble(
height.getText() ) );
//format the lenght of the returned value
DecimalFormat df = new DecimalFormat("#0");
String b = df.format(BMI);
System.out.println( b );
//print the BMI as value .setText( buffer.toString() );
}
catch (NumberFormatException e1)
{
JOptionPane.showMessageDialog(this,
"<html>" +
"<h3>The entered values are in
the wrong format!</h3>" +
"<h4>Please use \".\" instead
of \",\" as comma symbol!</h4>" +
"</html>",
"Wrong format!",
JOptionPane.ERROR_MESSAGE,
null);
e1.printStackTrace();
}
}
}
As you see my problem just exists if the user uses a "," instead of a
"." as a comma symbol (I'm Austrian and the "," is used like the "." in
the US).
Thanks in advance
Philipp
Philipp Weissenbacher - 10 Mar 2004 22:03 GMT
I solved it.
I simply read the content of the TextField into a StringBuffer, then
replaced the "," by a "." and everything works just fine.
Philipp
Chris Smith - 11 Mar 2004 03:49 GMT
> I solved it.
>
> I simply read the content of the TextField into a StringBuffer, then
> replaced the "," by a "." and everything works just fine.
Phillip,
That's an okay temporary solution, but you're still misusing the
Double.parseDouble method. Double.parseDouble is supposed to be used
for reading data that's been written previously by this application in a
text format (for example, in a properties file), and is being re-read.
It shouldn't be used for anything that's user-visible.
For user-visible data, you should parse the value using an instance of
NumberFormat, generally obtained by NumberFormat.getInstance(). It has
a method to parse numbers, and it will work properly for whatever the
locale of the intended user.

Signature
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation