How to format a double in Java
In Java, we can use String.format or DecimalFormat to format a double
, both support Locale based formatting.
1. String.format .2%f
For String.format
, we can use %f
to format a double, review the following Java example to format a double.
FormatDouble1.java
package com.mkyong.io.utils;
import java.util.Locale;
public class FormatDouble1 {
public static void main(String[] args) {
String input = "1234567890.123456";
double d = Double.parseDouble(input);
// 2 decimal points
System.out.println(String.format("%,.2f", d)); // 1,234,567,890.12
// 4 decimal points
System.out.println(String.format("%,.4f", d)); // 1,234,567,890.1235
// 20 digits, if enough digits, puts 0
System.out.println(String.format("%,020.2f", d)); // 00001,234,567,890.12
// 10 decimal points, if not enough digit, puts 0
System.out.println(String.format("%,.010f", d)); // 1,234,567,890.1234560000
// in scientist format
System.out.println(String.format("%e", d)); // 1.234568e+09
// different locale - FRANCE
System.out.println(String.format(
Locale.FRANCE, "%,.2f", d)); // 1 234 567 890,12
// different locale - GERMAN
System.out.println(String.format(
Locale.GERMAN, "%,.2f", d)); // 1.234.567.890,12
}
}
Output
Terminal
1,234,567,890.12
1,234,567,890.1235
00001,234,567,890.12
1,234,567,890.1234560000
1.234568e+09
1 234 567 890,12
1.234.567.890,12
2. DecimalFormat (#,###.##)
This example uses DecimalFormat
to format a double; it also supports locale.
FormatDouble2.java
package com.mkyong.io.utils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class FormatDouble2 {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#,###.##");
// different locale - GERMAN
DecimalFormat dfGerman = new DecimalFormat("#,###.##",
new DecimalFormatSymbols(Locale.GERMAN));
String input = "1234567890.123456";
double d = Double.parseDouble(input);
System.out.println(df.format(d)); // 1,234,567,890.12
System.out.println(dfGerman.format(d)); // 1.234.567.890,12
}
}
Output
1,234,567,890.12
1.234.567.890,12
The comma is a grouping separator!
For both String.format
or DecimalFormat
, the comma "," is a grouping separator, the result will vary on locale.
In most "English" locales, the grouping separator is also a comma ","; For non-English locale like German, the grouping separator is a period "."
References
About Author
Comments
Subscribe
0 Comments