Results 1 to 7 of 7

Thread: A Java Question

  1. #1
    Senior Member Falcon21's Avatar
    Join Date
    Dec 2002
    Location
    Singapore
    Posts
    252

    Lightbulb A Java Question

    How do I convert a floating point number to a number containing only a maximum of 2 decimal digits, just as in currency?
    Thanks.

  2. #2
    Custom User
    Join Date
    Oct 2001
    Posts
    503
    As far as I am aware, the easiest way to do this in java would be to use the NumberFormat class.

    Go to java.sun.com and load up the api help for whatever version of java you are using and search for NumberFormat. You should find all the info you need.

    ac

  3. #3
    gothic is right, easiest way is through a NumberFormat or a DecimalFormat (subclass of Number)... the API specifications for that class can be found here: http://java.sun.com/j2se/1.4.2/docs/...malFormat.html

  4. #4
    Custom User
    Join Date
    Oct 2001
    Posts
    503
    I tried...I really tried, but that damn nick of yours just wouldn't let me :P

    ac

  5. #5
    Originally posted here by gothic_type
    I tried...I really tried, but that damn nick of yours just wouldn't let me :P

    ac
    Don't worry about it, it's better this way.

  6. #6
    Senior Member Falcon21's Avatar
    Join Date
    Dec 2002
    Location
    Singapore
    Posts
    252
    Hello, I am very new to Java and have not yet know how to use API. Can anyone give me an example on how to format a number let say 123.123456789 into 123.12 using the NumberFormat class?

  7. #7
    Since you only want it formatted to the hundredth decimal place, I use the getCurrencyInstance() method. Obviously this won't run because it is just a sniplet of code.

    Code:
    import java.text.NumberFormat;
    ...... (Assume proper code is in here)
    
    double aLongNumber = 658.156168;
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    
    System.out.println(fmt.format(aLongNumber));
    Anyways, that would print out a formatted aLongNumber with decimals up to the hundredth spot. If you wanted to set that value in a variable, you'd just create another double variable and set the fmt.format(aLongNumber) to it.

    - dave

    [edit]
    I write like a retard sometimes. =P

Posting Permissions

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