Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to limit decimal places... ...Math.round()??

Status
Not open for further replies.

MissouriTiger

Programmer
Oct 10, 2000
185
US
How can I limit the fractional decimal places of a double? I found an old post on this forum which suggests Math.round(). But that returns a long, which isn't even a floating point type. As a simple example, how might I limit the following output to 1 fractional decimal place?

System.out.print
(absoluteError = Math.abs(guessWt - realWt));

_______________________________________
Constructed from 100% recycled electrons
 
May be the best way to achieve is to build your own function combining the Double.toString method and a stringTokenizer like this :
Code:
public String cutDecimals(Double dblValue, int nbDecimals) {
  String tmp = Double.toString(dblValue);
  StringTokenizer st = new StringTokenizer(tmp, ".", true); 
  // or "," (in function of your locals settings)
  String returnStr = st.nextToken() + st.nextToken() + st.nextToken().subString(0, nbDecimals - 1);
  return returnStr;
}

Beware : I didn't put any exception trap in this code. Water is not bad as soon as it stays out human body ;-)
 
Try this:
System.out.print(absoluteError=
((double) Math.round(Math.abs(guessWt-realWt)*10))/10));

If you want other than 1 dec, change the constants (10) into a variable.

Otto
 
Actually I already discovered a diferent way:

Declare-
DecimalFormat df1 = new DecimalFormat("####.00");

Then,

df1.format(arrayGuessWt)


_______________________________________
Constructed from 100% recycled electrons
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top