This question already has answers here:
How to format decimals in a currency format?
(22 answers)
Closed 8 years ago.
I have a Java Android app that deals with tips. When I take in the double of bill amount and tip percent, I parse them to to strings to display later.
How can I easily format the doubles to make the currency more readable at the end? Instead of looking like $1.0 it would be $1.00.
The code I have mentioned is:
final EditText amt = (EditText) findViewById(R.id.bill_amt);
final EditText tip = (EditText) findViewById(R.id.bill_percent);
final TextView result = (TextView) findViewById(R.id.res);
final TextView total = (TextView) findViewById(R.id.total);
double amount = Double.parseDouble(amt.getText().toString());
double tip_per = Double.parseDouble(tip.getText().toString());
double tip_cal = (amount * tip_per) / 100;
double totalcost = amount + tip_cal;
result.setText("Tip Amount : " + " $ " + Double.toString(tip_cal));
total.setText("Total Cost: " + " $ " + totalcost);
I would like result and total at the end to be the outputs that are nicely formatted doubles to 3 places. Thanks for any advice you can give.
you can user DecimalFormat to do the job for you
ex
double x = 1.0;
DecimalFormat decimalFormat = new DecimalFormat("$#0.00");
String text = decimalFormat.format(x);
[enter link description here][1]
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Related
I am having issues with String msg3 being displayed in my JOptionPane. When run I get a "String cannot be converted to int" error. If the 3 different strings are separated into their own panes the program will run, however, I need them all to be in the same one. Thank you for any advice/ help in advance.
//add all of the expenses together
double total = airfare1 + carRent1 + parking1 + reg1 + (lodge1 * numberOfDays1) + (meals * numberOfDays1);
String msg1;
msg1 = String.format("Total cost: $%,.2f\n Allowed expenses: $%,.2f\n", total);
//Calculate the allowable reinbusement
double allow = airfare1 + carRent1 + ( pfees * numberOfDays1) + reg1 + (lfees * numberOfDays1) + (meals * numberOfDays1);
String msg2;
msg2 = String.format("Allowed expenses: $%,.2f\n", allow);
//calculates the total amount to be paid back
double pback = total - allow;
String msg3;
msg3 = String.format("Amount to be paid back: $%,.2f\n", pback);
//display the totals using joptionpane
JOptionPane.showMessageDialog(null,msg1,msg2,msg3);
See the official documentation
The argument that you passed msg3 is String, but method accepts integer. There is no direct conversion from String to int.
I want to format some numbers in our jsp pages.
first i define some resources in my porperties
format.number.with2Decimal={0,number,#0.00}
......
Question1:
i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00
who can tell me the differences between them? thanks!
Question2:
if i define a BigDecimal type in my action
BigDecimal number1;
Then my page should using a format to show this value,
1.if number1=null then show -NIL-
2.if number1=0 then show -NIL-
3.if number1>0 then show 1.00,3434.98 .....
please ignore number<0
Question3:
change number1 to a String,
1.if number1=null or empty or blank then show -NIL-
2.if number1=Hello then show Hello ....
could you give me help?
Here you go :
<s:property value="getText('{0,number,#,##0.00}',{profit})"/>
This is how I format numbers in my projects. You can use it with <s:if> to attain what you require.
Question1: i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00 who can tell me the differences between them? thanks!
0 means that a number must be printed, no matter if it exists
# means that a number must be printed if it exists, omitted otherwise.
Example:
System.out.println("Assuming US Locale: " +
"',' as thousand separator, " +
"'.' as decimal separator ");
NumberFormat nf = new DecimalFormat("#,##0.0##");
System.out.println("\n==============================");
System.out.println("With Format (#,##0.0##) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
nf = new DecimalFormat("#,000.000");
System.out.println("\n==============================");
System.out.println("With Format (#,000.000) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
Running Example
Output:
Assuming US Locale: ',' as thousand separator, '.' as decimal separator)
==============================
With Format (#,##0.0##)
------------------------------
1234.0 = 1,234.0
123.4 = 123.4
12.34 = 12.34
1.234 = 1.234
==============================
==============================
With Format (#,000.000)
------------------------------
1234.0 = 1,234.000
123.4 = 123.400
12.34 = 012.340
1.234 = 001.234
==============================
In Struts2, you can apply this kind of format with the getText() function from ActionSupport.
P.S: Question 2 and 3 are trivial (and messy).
How can I input a decimal or double number as it is? I want if I input .56 it saves in the database as .56 not 1 because its rounding up and I want to ignore the rounding...
This is servlet, well I have beans and its also set to double; I also tried DecimalFormat but still not working or maybe I just don't know how to use it.
neutrophils = rs.getInt("neutrophils");
monocytes = rs.getInt("monocytes");
eosinophils = rs.getInt("eosinophils");
basophils = rs.getInt("basophils");
lymphocytes = rs.getInt("lymphocytes");
total= (neutrophils + monocytes + eosinophils + eosinophils + basophils + lymphocytes);
I made it like this, I changed the value of datatype to VARCHAR but the error is java.lang.NullPointerException; why is that?
neutrophils = Double.parseDouble(rs.getString("neutrophils"));
monocytes = Double.parseDouble(rs.getString("monocytes"));
eosinophils = Double.parseDouble(rs.getString("eosinophils"));
basophils = Double.parseDouble(rs.getString("basophils"));
lymphocytes = Double.parseDouble(rs.getString("lymphocytes"));
bands = (neutrophils + monocytes + eosinophils + eosinophils + basophils + lymphocytes);
If rs is ResultSet you can simply use rs.getDouble. If for some reason you don't want to use it, get the result as a String and then convert
Double.parseDouble(rs.getString(ColumnLabel));
I'm just starting to play around with android app.
I have an text field to input numbers but somehow I can only type in regular integers without decimals.
any idea what I can do so I can input decimals too?
This is what I have..
public void onClick(View arg0) {
EditText edit = (EditText)findViewById(R.id.editText1);
TextView text = (TextView)findViewById(R.id.textView1);
String input = edit.getText().toString();
float num = 0;
try {
num = Integer.parseInt(input);
} catch (NumberFormatException e) {
input = "0";
}
double newNum = num * 1.12;
DecimalFormat df = new DecimalFormat("###.##");
text.setText(input + " * 12% = " + df.format(newNum));
Add the following attribute to your EditText in xml:
android:inputType="numberDecimal"
This will inform the keyboard to enter decimals.
if you want to get decimal number keyboard you should add inputType with value numberDecimal in EditText xml file:
android:inputType="numberDecimal"
And if you want to use comma and dot also, you should add digits also in EditText xml:
android:digits="0123456789.,"
and when you get that result in Java, don't forget to replace dot with comma because Double and Float can only parse dot separated text:
String test = "12,34";
String changed = test.replace(",",".")
float value = Float.parseFloat(changed)
All in the title.., I'm looking for a safe way to format all Double in this manner, some other examples:
1000 ==> 1.000
1500 ==> 1.500
22000 ==> 22.000
1555005 ==> 1 555.005
I have looked in this link but not helped...
there is a safe way to do that ? THX in advance
You want to print your input number divided by a thousand, using a decimal dot and space as thousand separator. The safe way is to first convert to BigDecimal, scale by 10-3, then print it using DecimalFormat.
final DecimalFormat f = new DecimalFormat("#,###.000");
final DecimalFormatSymbols s = new DecimalFormatSymbols();
s.setGroupingSeparator(' ');
s.setDecimalSeparator('.');
f.setDecimalFormatSymbols(s);
final double input = 1_555_005;
final BigDecimal x = new BigDecimal(input).scaleByPowerOfTen(-3);
System.out.println(f.format(x));
prints
1 555.005
Note that setting grouping/decimal separators explicitly like here is not the orthodox way to do this: normally you would let the Locale setting dictate the number format.
this is taken from here
static public void displayNumber(Locale currentLocale) {
Integer quantity = new Integer(123456);
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String quantityOut;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut + " " + currentLocale.toString());
System.out.println(amountOut + " " + currentLocale.toString());
}
This example prints the following; it shows how the format of the same number varies with Locale:
123 456 fr_FR
345 987,246 fr_FR
123.456 de_DE
345.987,246 de_DE
123,456 en_US
345,987.246 en_US
Always use the java formatting API. There is a nice tutorial on number formatting at - http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html.
You can get a locale based formatter for French and format:
NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
For French the output will be something like this:
###,###.### 123 456,789 fr_FR