Java's DecimalFormat method rounds up by force. How do we prevent that?

John Doe ·

1152 Views

In https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

A browser with JavaScript enabled is required for this page to operate properly. Documentation The Java™ Tutorials Hide TOC Formatting Numbers and Currencies Using Predefined Formats Customizing Formats Dates and Times Using Predefined Formats Customizing

value: 123456.789

pattern: ###.##

output: 123456.79

The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.

 

We can prevent that like this.

package com.bad.blood.test;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Test {
	
	public static void main(String args[]) {
		
		double irr = 9.7485232;
		DecimalFormat df = new DecimalFormat("###.00");
		String str = df.format(irr);
		System.out.println(str); // 9.75
		
		// method 1
		String str2 = String.valueOf(irr);
		System.out.println(str2.substring(0, str2.indexOf('.') + 3)); // 9.74
		
		// method 2
		System.out.println( (double)(int)(irr * 100) / 100 ); // 9.74
		
		// method 3
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(2);
		nf.setRoundingMode(RoundingMode.DOWN);
		nf.setGroupingUsed(true);
		System.out.println(nf.format(irr)); // 9.74
	}

}

output:

9.75
9.74
9.74
9.74