DecimalFormat WITHOUT scientific notation - java

I have a DecimalFormat like this:
DecimalFormat df = new DecimalFormat("#,###.###");
Then I have 3 methods which just return a float value for time, potential and current, with many decimals in case of the two last ones. So I'm trying to get an output message with the 3 values formated, so:
System.out.println("t="+df.format(getTime())+"(s), v="+df.format(getPotential())+"(V), i="+df.format(getI())+"(A)");
Time just count seconds from 0 to 10, without any decimal, and looks ok until it gets to 10. Then it shows 1E+1. I just don't understand why, since I have read at the API and it shouldn't be in scientific notation if I don't use an 'E' character at the DecimalFormat.
Also, potential goes from 0 to a certain value, using 3 decimals. Looks OK, but from 0 to 0.01, it appears with 4 decimals, being the last one always 0.
Any explanation to this behaviour of DecimalFormat? What am I doing wrong?

Maybe it would be simpler to use printf in your case :
System.out.printf("t=%d(s) v=%.2f(V) i=%.2f(A)\n", getTime(), getPotential(), getI());

Related

DecimalFormat not rounding correctly for specific case

I have encountered a rather unusual scenario in my coding. I have developed this app and it has been utilised for the past 6 months with no errors.
To simplify my problem.. I am using a decimalFormat to round up numbers and ensure that they are to 2 decimal places and this has been working perfectly.
However, a problem came up that was sent back to me and it was said that every other case works except for this specific one and it seems to be in particular just the number 4?
Case:
Total = 44.75
Mean = 4.475
MBW (2 decimal places) = 4.47 NOT 4.48
This led me to wonder is DecimalFormat always correct when rounding? the weird thing is this works when it is 1.475 it rounds to .48 and every number except for 4??
Anyone any ideas?
Java example:
final DecimalFormat df = new DecimalFormat("#0.00");
weight2 = 4.475
MBW = df.format(weight2);
The result above is still getting 4.47.. any normal rounding should be 4.48?
This is working for any other whole number such as 1.475 is 1.48, 2.275 is 2.48... why is the whole number 4 not working???
These numbers cannot be represented exactly as a double. Looking at the bit pattern of the numbers represented as a double:
1.475 -> 3ff799999999999a
4.475 -> 4011e66666666666
you see that the first is slightly larger than the exact value, while the other is slightly smaller than the exact value. So it is rounded down to 4.47.
You can also try the following experiment:
System.out.println(1.475 - 1);
System.out.println(4.475 - 4);
System.out.println(5.475 - 5);
The result is
0.4750000000000001
0.47499999999999964
0.47499999999999964

Display only 2 digits after decimal

bill[p][l][0] = new DecimalFormat("##.##").format(Double.parseDouble(i2[m][0]));
The code entered above is not working; input 10.0 gives 10 as output.
It is working - a # means the digit is only printed if it's relevant (see the documentation). Try using
bill[p][l][0] = new DecimalFormat("##.00").format(Double.parseDouble(i2[m][0]));
To format exactly up to two decimal places you should use ##.00 as ##.## will remove the trailing zeros from the value.
If you want to handle both positive and negative numbers I would recommend using BigDecimal since Double technically doesn't have any decimal values to truncate. Try something like this:
new BigDecimal(i2[m][0]).setScale(2, BigDecimal.ROUND_FLOOR)

Remove the last grouping separator when using DecimalFormat Grouping java

I want to format lengthy double numbers in my android calculator app
2 problems ...
First is that I want to enable Grouping by 3 so 1200 would be shown 1,200
. But for numbers like 1000 what I get is 1,
How can I get 1,000 for result ?
also another problem is that I want Results with up to 25 integer digits and 4 decimal fraction digits ... but even though I set Decimalformat maximum to 25, after number of integers surpasses 18, Digits turn to be zeros. for example what I want is
1,111,111,111,111,111,111,111,111
but I get
1,111,111,111,111,111,110,000,000,
Here's the code
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(4);
df.setMaximumIntegerDigits(25);
df.setGroupingUsed(true);
df.setGroupingSize(3);
String formatted = df.format(mResultBeforeFormatting);
what pattern should I use ?
Ok so for others who face this problem like me
for first part best pattern was
DecimalFormat df = new DecimalFormat("###,##0.####");
for second problem as "x-code" noted it apears there's no hope using double . should try using BigDecimal
I found answers to both parts of the question right here on StackOverflow.
First is that I want to enable Grouping by 3
Here are several solutions to the grouping problem.
another problem is that I want Results with up to 25 integer digits
In this case what's really happening is that Java doubles can't represent 25 decimal digits.
For this problem you might want to look at the BigDecimal class, which can represent the numbers in your example.

Formatting decimal places in Java

I'm trying to format a double to just 2 decimal places in Java.
I've read the following post:
How to round a number to n decimal places in Java
For some reason, every one of those methods fails to work on certain numbers I have..
For example:
DecimalFormat df = new DecimalFormat("#.##");
normalizedValue = Double.valueOf(df.format(normalizedValue));
If I print normalizedValue I get result similar to the following:
-78.64000000000001
18.97
59.469999999999985
-63.120000000000005
(Note: some are formatted correctly... some aren't)
So, these methods seem to round, but I need something that will remove all decimals after 2 decimal places... Any suggestions?
Thank you.
The string representation given by DecimalFormat.format(...) does indeed have only 2 digits in your example. But as soon as you reconvert it into a double those accuracy issues occur. A binary base format like double will always show such effects when you try to represent "exakt" decimal fractions. You may change to BigDecimal to get rid of such effects.

How to determine max size of DecimalFormat before it's shown with exponent?

I have number displayed in EditText that can go up to 20 character + 4 decimal before it's too long. I would like to have number that are longer than that displayed with de exposant at the end so it's not truncated.
ex: 123456789 will show as is
123456789123456789123456 is too long and will be displayed as 1.123456789E8 (just an example !)
I have tested this:
DecimalFormat df = new DecimalFormat("#.####");
df.setMaximumIntegerDigits(20);
But after 20char, the numbers are just not displayed correctly. ex: 123456789123456789123456 became 56789123456789123456 (trunked 4 first digit.)
Thank you !
The Decimal Formater java doc descibe how to handle the Exponent.
Scientific Notation
Numbers in scientific notation are
expressed as the product of a mantissa
and a power of ten, for example, 1234
can be expressed as 1.234 x 10^3. The
mantissa is often in the range 1.0 <=
x < 10.0, but it need not be.
DecimalFormat can be instructed to
format and parse scientific notation
only via a pattern; there is currently
no factory method that creates a
scientific notation format. In a
pattern, the exponent character
immediately followed by one or more
digit characters indicates scientific
notation. Example: "0.###E0" formats
the number 1234 as "1.234E3".
...
The more difficult part is how to switch betwenn normal and Scientific Notation.
I have done this by embedding two decimal formater in an choide formatter within an Messageformater:
MessageFormat format = new MessageFormat(
"{0,choice,0#{0,number,'#,##0.####'}|99999<{0,number,'000000.####E0'}}",
Locale.ENGLISH);
(This excample is with only 6 decimal places, but you can change it.)
The usage of an message format is a bit different to an decimal formater, because the format metthod expect an array of objects.
System.out.println(format.format(new Object[] { 123 }));
What it prints for (1, 12, 123, ...) is:
1
1.1
12
123
1,234
12,345
123456E0
123456.7E1
123456.78E2
123456.789E3
123456.789E4
123456.789E5
123456.789E6
You need to tune the pattern a bit that it matches your 20 diget requirement, but the way should be clear.
Even if I have showed that it worked, I would recommend to implement your own Formater which uses 2 decimal formater and an if condition.
E is used to Format the number in Exponential Notation. Is that what you're looking for?
new DecimalFormat("####E0")
I'm not sure what an exposant is.
Sorry, Exposant is Exponent in french !
This work, but I would like to have exponential format only when number is longer than 20 characters. And if it's 20 or less character, I want to have the 4 decimals if there's any...
Thanks Ralph ! Exactly what I was loking for !
Here what I have done:
MessageFormat df = new MessageFormat("{0,choice,0#{0,number,'#.####'}|9999999999999999999<{0,number,'#.######E0'}}",
Locale.ENGLISH);
EditText2.setText(String.valueOf(df.format(new Object[] { Float.valueOf(EditText1.getText().toString()) * 1024})));

Categories

Resources