How to make 0 display as 0.00 using decimal format? - java

I am using the following code to make numbers display with two decimal places and thousands comma separator.
public static String formatNumber(double amount){
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amount);
}
For other numbers it is ok but 0 is returned as ".00" I want it to be "0.00" What should I change?

The # means optional digit, so if you use 0 instead it will work:
DecimalFormat formatter = new DecimalFormat("#,##0.00");
BTW: I think you need 3 ### not 4.

Why not
return String.format("%.2f", amount);
That would format it correctly wouldn't it? (if amount is 123123.14233 then it would return 123123.14)
or
return String.format("%,.2f", amount);
for commas within the number. (if amount is 123123.14233 then it would return 123,123.14)

Related

How to store a value greater than "999" in double while using parseDouble function?

I am not able to store value greater than "999" while using parseDouble function. This is my code:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmt.getText().toString())));
It is only storing value upto "999" not greater than that. It does not allow me to store value "1000" or greater.
Error message:
java.lang.NumberFormatException: For input string: "123,456.78"
The default method NumberFormat.format(String) automatically puts a comma separating thousands when setting it to formatted text. This comma can not be parsed into a double datatype because it only accepts '.' as the decimal split character and numbers around it.
This can be seen by this test:
double amount = Double.parseDouble(formatter.format(Double.parseDouble("1000")).replace(",", ""));
If the number requires a comma then use the .replace() method to replace it when parsing it to a double. Otherwise use a custom instantiation for your Number formatter such as:
NumberFormat formatter = new DecimalFormat("0000.00");
I am working under the assumption that balanceAmt.getText().toString() is returning 123,456.78 or similar.
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmy.getText().toString().replace(",", ""))).replace(",", ""));
System.out.print(amount);
When you get the balance from balanceAmt, it has the comma, so you have to remove it. When if goes through the formatter, it re-adds the comma back, meaning you have to remove it again before the second parseDouble is done.

cant see two decimal value when number is in 10 series after formatting

I want to convert double value up to two decimals. It is working fine for values like 6779.77,22334.22 but it doesn't work for value 33445.90,3334.30 it shows only 33445.9 and 3334.3 values does not show 0.
Why is it so?
public static String formatAmount(String number) {
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,##,##,###.##");
return formatter.format(amount);
}
# means that trailing zeroes can be omitted. Instead, you should use the 0 format character:
DecimalFormat formatter = new DecimalFormat("#,##,##,###.00");
// Here -------------------------------------------------^

Fromatting double value to 2 decimals

i want to format my double value to 2 decimals and then make it "text to speech".
this is my code:
mares = mass * acc;
DecimalFormat df = new DecimalFormat("#.00");
df.format(mares);
String mare = String.format("The force is %f", df);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
but it crashes, i don't know why, i put 5 and 6 and it should multiply them and give me 30.00 or something like that.
when i remove DecimalFormat the result is 30.00000000000000, i just don't like it, too many zeros.
can someone help me please?
Thanks in advance!
Your DecimalFormat is returning the formatted string, but you are ignoring it, and passing it as an argument to String.format, which certainly isn't right.
Assign the return of df.format to a string for further reference:
String mare = df.format(mares);
Or pass the numeric value directly to String.format, with the appropriate format precision specified:
String mare = String.format("The force is %.2f", mares);

Formatting in java

Good day.
I need to format a number in java.
So far I have this:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
System.out.println(new Double(df2.format(balance)).doubleValue());
But it prints out this
110.0
121.0
133.1
146.41
161.05
But I need it to be with two digits in fraction part. How do I do it?
You don't have to get double value from formatted string.
Just use formatted string, which is returned from format() method of DecimalFormat.
So your code should be like the following:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
...
System.out.println(df2.format(balance));
Your original code:
System.out.println(new Double(df2.format(balance)).doubleValue());
What you did in your code is: format the double value to string(which is formatted as you specified in the DecimalFormat instance). Then you convert the formatted string to Double instance and get double value from the object, which is double. And then printed it to console. So the formatted string is gone, and the double value is printed as normal.
"But I need it to be with two digits in fraction part. How do I do it?"
DecimalFormat df2 = new DecimalFormat( );
df2.setMinimumFractionDigits(2);
df2.setMaximumFractionDigits(2);
System.out.println(df2.format(balance));
You could also use the setMinimumFractionDigits method of DecimalFormat
df2.setMinimumFractionDigits(2);
your decimal format is right, but
what you are doing before you print this out is new Double(df2.format(balance)) which create new instant of double, which ignores your formatting.
so if you want to display or log your value df2.format(balance) this should be enough
ie:
System.out.println(df2.format(balance));
Try this pattern for formatting #,###,###,##.##-
DecimalFormat df2 = new DecimalFormat( "#,###,###,##.##" );
System.out.println(df2.format(balance));
This should be sufficient:
DecimalFormat df2 = new DecimalFormat("#,##0.00");
System.out.println(df2.format(balance));
The grouping for separator will follow "the interval between the last one and the end of the integer". So there is no benefit from over-specify. Example from the documentation of DecimalFormat:
The grouping separator is commonly used for thousands, but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Another thing is that .format() method already output a String, so there is no point in converting it to double. It will cause Exception to be thrown when balance is more than 1000 (the point when separator comes into effect, and Double class cannot parse the String with separator).

How to make strings from floating-point numbers with '.' (dot) as a decimal separator and not more than 3 digits after floating point?

I have this code:
public String formatDouble(double d) {
return String.format("???", d); //Should I use NumberFormat here?
}
For the sample input:
1.00
1,00
1,23
1.234567
I would like to get this output:
1
1
1.23
1.234
How can I configure the pattern (or maybe NumberFormat instance) for producing the correct output?
This would do roughly what you need:
Decimalformat df = new DecimalFormat("0.###");
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);
However, the decimal separator (the dot) will be dependent on current locale. To override it, you may want to provide your own format symbols (see DecimalFormat.setDecimalFormatSymbols()).
Simple way: String.format("%.2f", 1234.23)
If you need thousand separator, add a comma before the dot: String.format("%,.2f", 1234.23) -> the result: 1,234.23.
DecimalFormat should do what you need.

Categories

Resources