Setting precision in Java - java

If I want a double to have 9 decimal places, do I have to convert it to a string and then back to a double to do this (string methods are the only methods I'm seeing for setting the precision)?. In any case, what is the conventional way for setting the precision for a double if, for example, I want my method to return a double with 9 decimal places.

You're getting confused between a double's internal representation and it's display. Internally double numbers are always stored the same way but you can of course use a formater like DecimalFormat to return 9 decimal points from your double number.

Use Big Decimal to get 9 decimal places
or
double d = 1.2345672626346;
DecimalFormat df = new DecimalFormat("#.#########");
System.out.print(df.format(d));

You can't control precision with primitives in Java. You need to use BigDecimal. Read this excellent tutorial..

You could also use:
DecimalFormat df = DecimalFormat.getInstance(Locale.getDefault());
df.setMinimumFractionDigits(9); //sets 9 digits after the '.'

String formatedString = String.format("%.2f");
it set the presition to 5 digit o any.
if you only want to print it use this way.
System.out.printf("%.5f",123.2342622467);

Related

Can you explain this output of DecimalFormat API?

I have a number with value
0.947
Now, I use DecimalFormat API of java.text with the following pattern and RoundingMode-
double numberToFormat = 0.947;
DecimalFormat restrictTo1DecimalPlace = new DecimalFormat("0.0%");
restrictTo1DecimalPlace.setRoundingMode(RoundingMode.DOWN);
String formattedString = restrictTo2DecimalPlace.format(numberToFormat);
Now, I was expecting the value of formattedString to be 94.7% but its 94.6%.
I know the value has been set to RoundMode.Down but then why does value of following are not rounded down -
0.9471 -> 94.7%
0.9447 -> 94.4%
The closest floating point number to 0.947 is actually
0.94699999999999995292654375589336268603801727294921875
This is what your computer stores as a double when you write 0.947.
Rounding that down gives you 94.6%.
That's life I'm afraid. If you want exact decimal behaviour then use a decimal type! See data type to represent a big decimal in java

Java formatting decimals to 2 digits precision

Right now I am doing this
DecimalFormat df = new DecimalFormat("#.##");
//usage: df.format(someDouble);
But I don't know if this is the correct way to "round off" the display of a double to 2 decimal points. Will this work even if the number of digits to the left of the decimal point > 1?
You should use:
DecimalFormat df = new DecimalFormat("#.00");
DecimalFormat df = new DecimalFormat("#.##"); means, that those decimal places are optional. You can see the difference when applying on 1.2 or 1.0.
--Documentation
To answer the question about the rounding, the documentation tell it :
Rounding
DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.
So this is up to you to set the RoundingMode that you want with the setter.
public void setRoundingMode(RoundingMode roundingMode)
Will this work even if the number of digits to the left of the decimal point > 1?
Yes it will.

Why Float return different value and how can i solve it, Java

I am using Float to saving value. But when i save it seven and more then value in Float its return me different format value for example..
Float f=1234567.98
then float return me in string
1.23457e+06
What means of this and how can i solve it. Kindly please help me about this
Thanks in Advance
It means one of two things. Either your preferred printing method only shows a certain number of digits by default, or you are requesting more precision than a Float offers. The wikipedia page for single precision floats says that you can expect 6-9 decimal digits will be represented accurately. So that's probably your problem. You should be able to solve it by using a Double to store your value and DecimalFormat to customize the output.
To format a decimal use:
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
In this case the format you want is ###.##
An example of using this would be
float f = 123456.78f;
DecimalFormat format = new DecimalFormat("###.##');
String formatted = format.format(f);
Note that if you are using this for monetary calculations you should use BigDecimal instead. Floats are an efficient way of storing real numbers, but they can only represent so many. Here is an example of using BigDecimal:
BigDecimal bd = new BigDecimal(123456.78f);
bd = bd.add(3.4f);
bd = bd.divide(4.3f);//this division with floats may have returned an inexact answer
bd.setScale(2);//Makes sure we only care about 2 decimal places
String strValue = bd.toString();

Rounding the scientific notation of BigDecimal

I would like to print a BigDecimal in scientific notation so that the there are, say, 5 digits after the decimal point. For example: -3.12345E-51, 9.12345E100
.setScale() does not work in this case, because I don't know in advance the exponent of number in scientific notation. Moreover, BigDecimal doesn't seem to have a getExponent() method.
What's the best way to achieve this? Thank you in advance.
You should use DecimalFormat to print numbers in specified format:
BigDecimal bigDecimal = new BigDecimal(-3.12345E-51);
DecimalFormat format = new DecimalFormat("0.#####E0");
System.out.println(format.format(bigDecimal));
Also you can configure count of fraction digits using method DecimalFormat#setMaximumFractionDigits(int):
DecimalFormat format = new DecimalFormat("0E0");
format.setMaximumFractionDigits(6);

Show only two digit after decimal [duplicate]

This question already has answers here:
how to convert double to 2 number after the dot? [duplicate]
(6 answers)
Closed 9 years ago.
How to get the double value that is only two digit after decimal point.
for example
if
i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));
this code generating 5.81403333.
But I want only 5.81.
So what shoud I do?
Use DecimalFormat.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
How about String.format("%.2f", i2)?
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Many other answers only do formatting. This approach will return value instead of only print format.
double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

Categories

Resources