Formatting the floating point values

suggest change

Floating-point numbers can be formatted as decimal text with String.format and the f conversion. These calls pass Locale.US so the decimal separator is .. The default locale may use a different separator.

import java.util.Locale;

// Two digits in the fractional part are rounded
String format1 = String.format(Locale.US, "%.2f", 1.2399);
System.out.println(format1); // "1.24"

// Three digits in the fractional part are rounded
String format2 = String.format(Locale.US, "%.3f", 1.2399);
System.out.println(format2); // "1.240"

// Rounded to two digits, filled with zero
String format3 = String.format(Locale.US, "%.2f", 1.2);
System.out.println(format3); // "1.20"

// Rounded to two digits
String format4 = String.format(Locale.US, "%.2f", 3.19999);
System.out.println(format4); // "3.20"

DecimalFormat can do the same. The symbols below also come from Locale.US. A later declaration of format in the same block would not compile, so each result has its own variable.

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);

// rounded with one digit fractional part
String format5 = new DecimalFormat("0.#", symbols).format(4.3200);
System.out.println(format5); // 4.3

// rounded with two digit fractional part
String format6 = new DecimalFormat("0.##", symbols).format(1.2323000);
System.out.println(format6); // 1.23

// formatting a floating-point value as a decimal integer
double dv = 123456789;
System.out.println(dv); // 1.23456789E8
String format7 = new DecimalFormat("0", symbols).format(dv);
System.out.println(format7); // 123456789

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents