when you use floating points and do the coding normally you get 4 decimal points. . but if i want to make it to 2 decimal points. how can the program should be. please help me out

here is the program i did

/**
* @(#)Average.java
*
*
* @author
* @version 1.00 2008/7/8
*/

import java.io.*;


public class Average {

public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
float x=0;
float num[]=new float[10];


for(int i=0;i<10;i++)
{
System.out.println("Enter the Value");
num= Float.parseFloat(br.readLine());
x += num;
}
float avg=x/10;

System.out.println("The Average is " +avg);

}


}

Recommended Answers

All 3 Replies

True solution - study the DecimalFormat API here -- http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int)

Here's a complicated and unrecommended alternative solution--

import java.text.*;

public class Time_To_Format{


	public static void main(String[] args) throws Exception{

		System.out.println(Time_To_Format.<Double>truncate(new Double(2.444444), 2));

	}

	static <E extends Number> E truncate(E num, int knockoff) throws Exception{
			E e = null;

			StringBuffer arg = new StringBuffer("" + num);

			int checked = 0, point = 0;

			for(int i = 0; i < arg.toString().length() - 1; i++){
				if(arg.charAt(i) == '.')
					point = i;
			}

			for(int i = point; i < arg.toString().length() - 1; i++){

				if(checked < knockoff)
					checked++;
				else arg.setCharAt(i, ' ');
			}

			String str = arg.toString();

			str = str.replace(" ", "");

			if(num instanceof Integer){
				e = (E)(Integer)Integer.parseInt(str);
			}
			else if(num instanceof Double){
				e = (E)(Double)Double.parseDouble(str);
			}
			return e;
	}
}

Stick with the first suggestion - use DecimalFormat.

Stick with the first suggestion - use DecimalFormat.

I already know there are a ton of errors in the above code, but when I got to about 60% done, I thought to myself "this isn't the best way - better he learn the API than reinvent the wheel."

Not that there's anything wrong with reinventing the wheel in some cases. For example, performance boosts in programs but even then it's probably best that everyone sticks to the standard API's for code readability and easily-editable code.

Be a part of the DaniWeb community

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