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.
Answer from Espo on Stack Overflow[Java] DecimalFormat vs NumberFormat?
What was the thought process behind the design of the NumberFormat class? Why doesn't it have a way to set a pattern?
Phone number breakdown (java problem) - How should I do it?
question: How to format digits into dollar amounts
Videos
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);
I find the area of an object and store it in a type double. If I want a specific number of decimal places, say 5, which one is better to use?
e.g. 4.55 > 4.55000,
But I guess maybe I need to understand the idea of decimal places. If a number is 4.555555, rounded to 5 decimal places, will it be 4.55556? If so, will the DecimalFormat be what I need to look into? I see if I do #.##### it will round down, but if I use zeroes, it will round normally like in math: #.00000.
If this is correct..can someone tell me the difference between number format and decimal format then? When to use each.