Can someone help me create a rounding routine? I have some mathematical calculations being done in a program that the final result is a double. The only trouble is, is when I want to display it, there are too many digits appearing. I have searched the Sun web site and others without finding anything that will help.

Recommended Answers

You should really dig into the API docs a bit. Depending on what you want to achieve you can use one of two classes at least to achieve what you want using only standard API functions.

Jump to Post

All 3 Replies

You should really dig into the API docs a bit. Depending on what you want to achieve you can use one of two classes at least to achieve what you want using only standard API functions.

Yep, you can use decimal format, or the Math.round(), but you'll be satisfied with the DecimalFormat class.

import java.text.DecimalFormat; 

public class DecimalTest 
{
	public static void main(String[] args) 
	{
		DecimalFormat dfMoney = new DecimalFormat("$###.##");
		DecimalFormat df2 = new DecimalFormat("###.##");
		DecimalFormat df3 = new DecimalFormat("###.###");
		DecimalFormat df4 = new DecimalFormat("###.####");

		System.out.println(dfMoney.format(294.489003));
		System.out.println(df2.format(294.489003));
		System.out.println(df3.format(5935.393432));
		System.out.println(df4.format(1323.23423));

	}
}

Here is the output:
$294.49
294.49
5935.393
1323.2342

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.