2 Replies - 5033 Views - Last Post: 13 March 2010 - 04:01 PM Rate Topic: -----

#1 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,682
  • Joined: 13-March 10

Limiting number of decimal places

Posted 13 March 2010 - 03:55 PM

When i write in my program

double pi = Math.PI;

This will give me a value of PI accurate to many decimal places, but what if i want to limit this number
lets say to 3 decimal places..
Is there such a method in Java?

(Im not talking here only about the value of Math.PI or Math.E, but about all double values that contain
many decimal places)
Is This A Good Question/Topic? 0
  • +

Replies To: Limiting number of decimal places

#2 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: Limiting number of decimal places

Posted 13 March 2010 - 04:00 PM

Use the numberformat class

import java.text.NumberFormat;

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);

public static void main(String[] args)
{
    double pi = Math.PI;
    System.out.println(nf.format(pi));
}


That will format Pi to 2 decimal places.

Check it out: http://java.sun.com/...mberFormat.html

I'd just like to point out that you could have just used NumberFormat.getInstance() for an even more "all-purpose" formatter.

There are also a gamut of other ways to do rounding, I just like the Format classes. :P

This post has been edited by zim1985: 13 March 2010 - 04:09 PM

Was This Post Helpful? 1
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10390
  • View blog
  • Posts: 38,451
  • Joined: 27-December 08

Re: Limiting number of decimal places

Posted 13 March 2010 - 04:01 PM

Yes- you can use the System.out.printf() or the String.format() methods, which work basically the same way. Here is a printf() example for three decimal places:
System.out.printf("Pi: %.3f", Math.PI); 



So where the %.3f is, Math.PI will be placed there instead rounded to 3 decimal places. Note that you can specify as many values using printf() as you want (so long as they don't exceed memory), and you can use other types like ints, Strings, etc., not just floating-point numbers (double, float).

For more information on String formatting, you can check out these tutorials:
http://www.java2s.co...tObjectargs.htm
http://java.sun.com/...ter.html#syntax
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1