No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".
An alternative is to use String.format:
double[] arr = { 23.59004,
35.7,
3.0,
9
};
for ( double dub : arr ) {
System.out.println( String.format( "%.2f", dub ) );
}
output:
23.59
35.70
3.00
9.00
You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.
Format a double to fixed decimal length - Support - Kotlin Discussions
Round double value to 2 decimal
How to round a double variable only have to decimal places
How Do I Keep Decimal Formatting To Just 2 Decimals
What is the most effective way to round numbers to two decimal places in C#?
Math.Round method, which allows you to specify the number of decimal places and the rounding strategy.Why choose decimal over double for financial calculations in C#?
How can midpoint rounding be controlled in C#?
MidpointRounding enum, which lets you define how to handle numbers that are exactly halfway between two possible rounded values.Videos
When I set number or currency formatting to 2 decimals, the cell displays as 2 decimals but the actual value still shows more. Is there a way to actually keep the cell value to limited decimals without using a rounding formula? Am I doing something wrong?