I have a simple calculation that uses doubles but I\'m getting an unexpected result and I can\'t understand why?
import java.util.Scanner;
public class Versa
Doubles (floating-point values in general) cannot always represent exactly what we think of intuitively as a precise value. This is because of the way in which floats are stored, and can vary from machine to machine and language to language. When you try to store 2.99
, the actual value that is stored may be very slightly different (e.g. 2.990000000000002
). This question gives a decent, quick overview of why.
You should therefore (as it says through the link) never use floating-point primitives to represent currency. Either use BigDecimal
, or keep track of two integers yourself (e.g. int dollars;
and int cents;
).
I believe this question has been asked a million times. You can find a good and quick description of it here Why not use Double or Float to represent currency?
If you are just fooling around and you want it to print properly use
String prettyNumber = String.format("%.2f", doubleNumber);
Which is going to print 2 floating points. It will look correct, but it is only correct if precision (in the magnitude of 10^-16 or so) is not of interest to you.
You cannot represent decimal values precisely whilst operating on doubles (or floats). Use BigDecimal instead.
Edit (2)
Example here:
BigDecimal amount = new BigDecimal("2.99");
amount = amount.add(new BigDecimal("25.00"));
System.out.println(amount.toString());
Ouput:
27.99
use DecimalFormat to display 2 digit after whole number
DecimalFormat f = new DecimalFormat("##.00");
String amt=f.format(amount);
System.out.print("We will bill $");
System.out.print(amt);
http://www.browxy.com/SubmittedCode/21519