Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Regular Coder
    Join Date
    Sep 2002
    Location
    Calgary, AB
    Posts
    179
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Decimals in Java

    How do you assign a certain number of decimal points in a java program?

    When I print out a message using System.out.println, the system prints out numbers with about 10 decimal places.

    Thanks,
    Nick!

  • #2
    Regular Coder
    Join Date
    Feb 2003
    Location
    California
    Posts
    925
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    import java.text.NumberFormat;
    ..................
          NumberFormat nf = NumberFormat.getNumberInstance() ;
          nf.setGroupingUsed(false) ;     // don't group by threes
          nf.setMaximumFractionDigits(2) ;
          nf.setMinimumFractionDigits(2) ;
          System.out.println("float unformatted " + d1 + " now formatted " + nf.format(d1));


    Jason

  • #3
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    620
    Thanks
    0
    Thanked 6 Times in 6 Posts
    it also depends on what type your variables are. Floats, doubles, ints...

    Otherwise the numberformat class is the way to go.

  • #4
    Regular Coder
    Join Date
    Sep 2002
    Location
    Calgary, AB
    Posts
    179
    Thanks
    0
    Thanked 0 Times in 0 Posts
    My variables are declared as doubles.

    Could someone please give me an example of how to implement the above code?


    Thanks,
    Nick!

  • #5
    teh Moderatorinator
    Join Date
    Sep 2004
    Location
    USA
    Posts
    2,472
    Thanks
    4
    Thanked 40 Times in 40 Posts
    That code is all you need:
    PHP Code:
    import java.text.NumberFormat;
    public class 
    decimals

    {
        public static 
    void main(String[] args)

        {
            
    NumberFormat nf NumberFormat.getNumberInstance() ;
            
    nf.setGroupingUsed(false) ;     // don't group by threes
            
    nf.setMaximumFractionDigits(2) ;
            
    nf.setMinimumFractionDigits(2) ;
            
    double d1 3.427223;
              
    System.out.println("float unformatted " d1 " now formatted " nf.format(d1));

        }



  • #6
    Regular Coder
    Join Date
    Sep 2002
    Location
    Calgary, AB
    Posts
    179
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ah, okay! I've got it.

    Thank You!!



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •