PDA

Click to See Complete Forum and Search --> : A Java Question


Falcon21
September 3rd, 2004, 03:11 PM
How do I convert a floating point number to a number containing only a maximum of 2 decimal digits, just as in currency?
Thanks.

gothic_type
September 3rd, 2004, 08:34 PM
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

God's Whore
September 3rd, 2004, 09:38 PM
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/api/java/text/DecimalFormat.html

gothic_type
September 3rd, 2004, 10:50 PM
I tried...I really tried, but that damn nick of yours just wouldn't let me :P

ac

God's Whore
September 4th, 2004, 05:43 AM
Originally posted here (http://www.AntiOnline.com/showthread.php?threadid=261676#post787273) 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.

Falcon21
September 4th, 2004, 07:58 AM
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?

God's Whore
September 4th, 2004, 02:59 PM
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.


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