How would I make a double value have a trailing zero in java. My program deals with currency. Ex. How do I to make 9.5 to 9.50?
Asked
Active
Viewed 2,009 times
0
-
https://stackoverflow.com/q/153724/10504469 might help you. – Jin Lee Jul 13 '19 at 01:42
-
a `double` doesn't know the concept of a decimal, as it uses binary fractions and doesn't maintain the precision of its fraction. You can however format it to a particular decimal representation as the answers have shown. The alternative is `BigDecimal` which does represent decimal fractions and keeps a precision too. But BigDecimal arithmetic is slower than `double` and takes more memory. – Erwin Bolwidt Jul 13 '19 at 02:44
-
See also [What is the best data type to use for money in Java app?](https://stackoverflow.com/q/8148684/5221149) – Andreas Jul 13 '19 at 03:38
3 Answers
1
For currencies, it would be better to use BigDecimal
class which doesn't lose precision. You can define the precision as scale
parameter.
If you want to display 9.50 to the user, use
String.format("%.2f", decimalValue)
where 2 is the number of decimal places you want to display.

Genhis
- 1,484
- 3
- 27
- 29
0
Assuming that you need to convert a double to a String with two decimal places, you have to use a DecimalFormat:
DecimalFormat df = new DecimalFormat("#0.00");
double doubleValue = 9.5d;
String stringValue = df.format(doubleValue); // "9.50"
But when you are dealing with currency, it's better to deal with integers/longs/BigIntegers of the lowest possible amount (1 cent, 1 satoshi, etc) to avoid floating point errors, so keep that in mind.

alexk745
- 38
- 11
0
If you're dealing with a currency, use the currency and internationalisation features of Java:
public static void main(String[] args) {
double iii = 9.5;
NumberFormat format = NumberFormat.getCurrencyInstance();
NumberFormat formatUS = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println("Format currency (default) : " + format.format(iii));
System.out.println("Format currency (Germany) : " + formatUS.format(iii));
}
This produces:
Format currency (default) : $9.50
Format currency (Germany) : 9,50 €

craigcaulfield
- 3,381
- 10
- 32
- 40