Reputation: 3270
I have a stupid question :
String str0 = "245.00";
String str1 = "45.00";
Double str3 = Double.parseDouble(str0) - Double.parseDouble(str1);
System.out.println(str3); =====> 200.0
Why it don't gives 200.00? (tested with Float too) And how to control number of digits after the comma?
Upvotes: 0
Views: 9988
Reputation: 1568
When stored as a string, 10 is different than 10.0, which is also different than 10.00. When stored as a double, they may not be equal. Never trust two doubles to be ==
/.equals()
the same.
To print a double with a certain number of decimal places, use the printf
method. For example:
String str0 = "245.00";
String str1 = "45.00";
Double str3 = Double.parseDouble(str0) - Double.parseDouble(str1);
System.out.println(str3); // 200.0
System.out.printf("%.2f", str3); // 200.00
Upvotes: 1
Reputation: 20029
To .0
comes from the default implementation of Java Double.toString()
.
To allow more control, use a Format
. See here: NumberFormat api doc and here DecimalFormat tutorial
For simple formatting, you can also use String.format()
, for example:
String.format("%02d", myNumber)
Or even print it directly using System.out.format
System.out.format("%.2f", myNumber);
Upvotes: 3
Reputation: 12363
This is not an answer but a general advice for doing floating point calculations.
You should use BigDecimal for calculations
public class BigDecimalExample {
public static void main(String args[]) throws IOException {
//floating point calculation
double amount1 = 2.15;
double amount2 = 1.10;
System.out.println("difference between 2.15 and 1.0 using double is: " + (amount1 - amount2));
//Use BigDecimal for financial calculation
BigDecimal amount3 = new BigDecimal("2.15");
BigDecimal amount4 = new BigDecimal("1.10") ;
System.out.println("difference between 2.15 and 1.0 using BigDecimal is: " + (amount3.subtract(amount4)));
}
}
Output:
difference between 2.15 and 1.0 using double is: 1.0499999999999998
difference between 2.15 and 1.0 using BigDecmial is: 1.05
This answer is adapted from http://javarevisited.blogspot.in/2012/02/java-mistake-1-using-float-and-double.html
Also you can read a very good article on the need for BigDecimal http://www.javaworld.com/article/2071332/the-need-for-bigdecimal.html
Upvotes: 3