FormattingNumbers - Java - Code with Mosh Forum
java - Use NumberFormat or DecimalFormat - Stack Overflow
java - How to make a number format? - Stack Overflow
How do I format a number in Java? - Stack Overflow
Videos
If you want to specify how your numbers are formatted, then you must use the DecimalFormat constructor. If you want "the way most numbers are represented in my current locale", then use the default instance of NumberFormat.
I had the same issue concerning locale. You can create a DecimalFormat object for a US locale by instantiating a NumberFormat and then casting it to a DecimalFormat. This is what Oracle says:
The preceding example created a DecimalFormat object for the default Locale. If you want a DecimalFormat object for a nondefault Locale, you instantiate a NumberFormat and then cast it to DecimalFormat. Here's an example:
NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
Use DecimalFormat()
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double d = 100.2397;
double d1 = new Double(df2.format(d)).doubleValue();
Output - d1 will be 100.24
You need to use a number formatter as shown in the example below:
NumberFormat myFormatter = new DecimalFormat("#.###");
double myNumber = 1234.5632;
String formattedNumber = myFormatter.format(myNumber);
and formattedNumber will be equal to "1234.563"
From this thread, there are different ways to do this:
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
f = (float) (Math.round(n*100.0f)/100.0f);
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.
You and String.format() will be new best friends!
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
String.format("%.2f", (double)value);