954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Number Rounding

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.

AQWst
Light Poster
31 posts since Jan 2005
Reputation Points: 10
Solved Threads: 0
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 
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

paradox814
Posting Whiz
351 posts since Oct 2004
Reputation Points: 13
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You