Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

double precision

Status
Not open for further replies.

yukeshean

Programmer
Aug 24, 2001
9
MY
dear all,
let say i have a number in string form. The number is 78.18 but is in Sring type. I have to get the number for 78.18 * 11 , which is in number data type, not String type. Therefore, i use Double.parseDouble()....but what i got at last is 859.9000000...01. Why? If i want to get the answer in 859.90 (in 2 precision), how should i do?

Thanks.

yukeshean
fyshean@hotmail.com
 
hi,
this code work good,
double d1 = java.lang.Double.valueOf("78.18").doubleValue();
double d2 = 11;
double sum = d1 * d2;
yehuda.
 
Dear klein,
I'm sorry ...I still got a number with more than 2 precision (e.g: 98.110000000000078).
Why???

Thanks
 
the toString method of a double number returns a string which is as precise as the number can get, and as always with floating point arithmetic, there will be errors, which result in tini tiny little decimals being tacked onto the number. if you just want 2 decimal places, multiply the number by 100, cast it into an 'int', and then print all but the last to digits, a '.', and the rest of the number:[tt]
double num = java.lang.Double.valueOf(string).doubleValue();
int temp = (int)(num * 100.0);
String double = (new Integer(temp)).toString();
String answer = double.substring(0, double.length() - 2) +
"." + double.substring(double.length() - 2
double.length());
[/tt]
this code is untested, but should illustrate how to do it.
good luck. "If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top