There's no difference in internal representation between 2 and 2.00. You can use Math.round
to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.
If you're only interested in formatting a value to two decimal places, look at DecimalFormat
- if you're interested in a number of decimal places while calculating you should really be using BigDecimal
. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available double
value".
Another option you may want to consider if you're always dealing with two decimal places is to store the value as a long
or BigInteger
, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…