|
-
Mar 27th, 2008, 05:56 AM
#1
Thread Starter
Fanatic Member
String/Number formatting
How can I format a number in java so that only two numbers are displayed after the decimal point?
I have tried using DecimalFormat with no luck.
Here is the code I used.
Code:
float newTotPrice = totPrice + Double.valueOf(myProduct.getPrice()).floatValue();
//For formatting a number
DecimalFormat df = new DecimalFormat("#.00");
//Format 'newTotPrice' so that only two digits are shown after the decimal point
df.format(newTotPrice);
//Show total price
lblTotPrice.setText("£ " + newTotPrice);
This doesn't work as I got a result of "£ 509.97003"
Last edited by x-ice; Mar 27th, 2008 at 11:49 AM.
-
Mar 27th, 2008, 10:26 AM
#2
Re: String/Number formatting
Code:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Util {
public static void main(String[] args) {
double d = 10.45;
NumberFormat formatter = DecimalFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
System.out.println(formatter.format(Math.PI));
}
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Mar 27th, 2008, 11:40 AM
#3
Thread Starter
Fanatic Member
Re: String/Number formatting
When the number of more than 999 the formatter seems to put a comma in. How can I set it so that it doesn't do this?
E.g. 1,023.23 should be 1023.23
-
Mar 27th, 2008, 11:49 AM
#4
Thread Starter
Fanatic Member
Re: String/Number formatting
Code:
formatter.setGroupingUsed(false);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|