Decimal Format conversion issue - java

I'm using DecimalFormat in order to convert double to string like this:
DecimalFormat df = new DecimalFormat("###.###");
df.format(km);
The problem is, although the variable km has the value of 9.655195710258606E-5, the result of the df.format method returns 0 as string.But I expect something like 9.655 instead of 0.
Any help & suggestions will be appreciated
Thank you for your concern

It works as it should. The string "9.655" would be wrong. The value is actually 0.00009655 and if you round it to 3 decimal places you get "0".
To see some more digits, you can use more decimal places in the format #.###### or force scientific notation with a format like this #.###E0.

In the end of these numbers, the E(x) represents the exponent. E-5, means the exponent is -5, which means the actual number is 9.655 * (1/(10^5)).

Related

making double readable by adding '.' , ',' , trimming (not rounding) so only 2 last digits possible?

I've been looking for a way to convert a double, which is big to a readable String.
The double:
double myValue = 1000000000000000.123456789;
Which when printed out gives me this:
1.0000000000000001E15
The result im looking for would be this:
1.000.000.000.000.000,12
I've been searching for this for days but i couldn't find a solution for this unfortunately so i thought maybe i could ask here:) thanks for reading!
If you are interested in setting your own separator characters (i.e. not using the default for your locale) then you can do the following:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator('.');
symbols.setDecimalSeparator(',');
DecimalFormat format = new DecimalFormat("#,##0.00", symbols);
System.out.println(format.format(100000000000.123456789));
You also mentioned rounding in your question. Unfortunately that has nothing to do with the formatting at all - you are hitting the limit of precision for double in Java. A double is a 64 bit floating points which gives you 15-16 digits of precision. You can verify this by checking the following expression in Java: 1000000000000000.123456789 == 1000000000000000.1.
So, in reality what is happening is that once you have assigned your value to the myValue variable it has already been rounded. It doesn't matter how you format it from that point you won't get the precision back.
If you need greater precision than double you should look at BigDecimal that supports arbitrary precision.

Remove trailing numbers

Why I get trailing so many numbers when I run below code?
BigDecimal lat = new BigDecimal(0.0077);
System.out.println(lat);
output >>
0.00770000000000000024702462297909733024425804615020751953125
I want to print exactly what I entered. How can I do this?
Most finite decimal fractions cannot be exactly represented by floating-point, so that is the approximation you get when you create the floating-point literal 0.0077.
To avoid the problem, use the constructor BigDecimal(String val) instead:
BigDecimal lat = new BigDecimal("0.0077");
As #TimB points out, if you already have a double value, you can also use:
BigDecimal lat = BigDecimal.valueOf(doubleVal);
Also, here is the mandatory reference to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
When you have a number like 0.077 this cannot be exactly represented and in fact you get a number which is almost this, but with a small error. When you print this number as a string, the code to do this "knows" to discard the small error and you see the number you expect.
BigDecimal tries to give you a faithful representation and it is doing what it should even if this is surprising. What you want to use is the following method
BigDecimal bd = BigDecimal.valueOf(0.077);
In this case the BigDecimal takes the value as it would be printed, instead of the true value represented.
why is it so long?
To accurately represent a 53-bit fraction (double has a 53-bit mantissa) you need 53 decimal digits. e.g. every time you multiple by 10 to get another digit, you multiple 2 (and 5) which makes the lower bit 0 and eventually you guarentee to have all 0 bits and no more digits.
Try this:
System.out.println(String.format("%.4f",lat));
where 4 in %.4f specified how many decimal places you want to display
Note that this will only format your output display. the actual value of lat however still 0.00770000000000000024702462297909733024425804615020751953125
You can also use NumberFormat and specify the fraction digits setMinimumFractionDigits(4)
BigDecimal lat = new BigDecimal(0.0077);
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(4);
System.out.println(nf.format(lat));
BigDecimal lat = new BigDecimal(0.0077);
lat=lat.setScale(4,RoundingMode.HALF_EVEN);
System.out.println(lat);

How can I convert a double to a string without notation and with a high amount of accuracy in Java?

I'm trying to convert a double to a string without notation, and tried this:
f= Double.valueOf(c.getString(c.getColumnIndex(NotesDbAdapter.KEY_VALUE)));
NumberFormat formatter = new DecimalFormat("###.##############");
However, the value of 7^3^7 is returning as: 558546000000000000 opposed to 558545864083284007. As always help would be greatly appreciated.
You already had the value as a String. Why convert it to double at all?
You can't get precision out of a double that it cannot hold. 558545864083284007 has 18 decimal digits. A double has 53 bits of binary precision, which is about 15.9 decimal digits. Google for 'What every computer scientist should know about floating-point'.
###.############## is not a suitable formatting mask for 558545864083284007.
If you already have the huge decimal number in string format, try using the BigDecimal class, something like this:
BigDecimal bigDecimalValue = new BigDecimal("1234567890123456789012345678901234567890.54321");
LOGGER.info("bigDecimalValue: {}", bigDecimalValue.toPlainString());
You should get back the original value with no precision loss:
bigDecimalValue: 1234567890123456789012345678901234567890.54321

What should i have to change in that function to get the 0.00 like effect?

For to get the fraction point value upto two decimal Point i use this function.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("##.##");
return Double.valueOf(twoDForm.format(d));
But While there is a value like "5.50" then with this function i got only "5.5".
Instead of that i want to get the 5.50 with the above function then what should i have to change ??
Please give me the Updated function or any suggestion to change the output like "0.00".
Thanks.
Your example works fine for rounding numbers to 2 digits. But you will lose trailing zeros, because numeric variables (double, float, ...) do not store any formating information.
If you want to see trailing zeros (like 5.50) you have to format the numbers on output:
DecimalFormat twoDForm = new DecimalFormat("#0.00");
System.out.println(twoDForm.format(d));
Use the format:
new DecimalFormat("#0.00")
When you use #, zero values display as absent. Using a 0 will ensure that either a digit or a 0 is displayed.
DecimalFormat.format returns a String (not a StringBuffer), which you are then getting the Double.valueOf(...). You then return the double value, which I assume when you print it uses it's own toString() to be displayed. You need to run the DecimalFormat.format on the double value returned.

How do I format a decimal value to have appropriate amount of trailing spaces

I have a double value which could be either 9.2 or 13.45 or 198.789 or 110.8.
How do I format this to 9.2000 or 13.4500 198.7890 or 110.8000
This SO post can be of help.
Look into the Decimal Format class.
new DecimalFormat("#0.0000").format(9.2); //"9.2000"
See: The DecimalFormat Class under
http://download.oracle.com/javase/tutorial/java/data/numberformat.html
Have a look at DecimalFormat
You can use String.format() to some extent. For example:
String.format("%07.3f", 1.23d); //prints 001.230
The format is %0<width>.<precision>f where, <width> is the minimum number of character (including the dot) that should be printed padded with 0's (in my example there are 7 characters); <precision> is the number of digits after the decimal point.
This method will work for simple formatting, and you cannot control the rounding (rounding is is half-up by default).

Categories