How to round 0.0 to 0.00 in java? - java

I have used the following function
float val=0.0;
DecimalFormat toTheFormat = new DecimalFormat("#.##");
float value=Float.valueOf(toTheFormat.format(val));
But its not suitable for all conditions like "0.0" still "0.0". Its not scale up to "0.00".

Use
DecimalFormat toTheFormat = new DecimalFormat("0.00");
to round to 2 significant digits

try
DecimalFormat toTheFormat = new DecimalFormat("#.00");

Your approach is mistaken. Rounding is a numeric operation that takes a number x and returns another number y which approximates x and has the property that the decimal expansion has only so many digits. Example:
0.123 --> 0.12
But 0.0 and 0.00 are the exact same numbers, there is no point in rounding. What you (maybe) want is to format a number in a certain way on output. For this, see the other answers.

If I use DecimalFormat toTheFormat = new DecimalFormat("#.00");
am getting output as .00 not 0.00
so this would be the correct code
DecimalFormat toTheFormat = new DecimalFormat("#0.00");

Related

Java DecimalFormat HALF_UP rounding error

I'm using the DecimalFormat with HALF_UP rounding mode and I have an escenery where is not working correctly and I don't know why.
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_UP);
float tmp = (float) (0.5 * 1.05);
df.format(tmp);
float mul = Float.parseFloat(df.format(tmp));
The mul variable value I hope have 0.53 value and I received 0.52 value.
I'm using the Java 1.8.0_131.
SOLVED FINAL CODE
BigDecimal mul = new BigDecimal(0.5).multiply(new igDecimal(1.05));
mul = mul.setScale(2, RoundingMode.HALF_UP);
System.out.println(mul);
You are using the float datatype.
This datatype is not able to precisely hold the value 0.525. See this code for making it clear:
float value = (float) (0.5 * 1.05);
DecimalFormat df = new DecimalFormat("#.########################");
System.out.println(df.format(value));
This prints out:
0.5249999761581421
Rounding such a value with the mode RoundingMode.HALF_UP will correctly yield 0.52.
The double value seems to be able to precisely store the value 0.525:
double value = 0.5 * 1.05;
DecimalFormat df = new DecimalFormat("#.########################");
System.out.println(df.format(value));
This will print the expected value:
0.525
Rounding that value with the mode RoundingMode.HALF_UP will now yield 0.53!
Caution: Even the double datatype does not store the value precisely!
Look at #MarkDickinson's comment. The stored value is 0.52500000000000002220446049250313080847263336181640625 which happens to be larger than 0.525 and only rounds by accident to the expected value.
So what to do?
The data types float and double are binary-based, whereas we humans tend to think decimal-based when dealing with numbers. Read the article "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for much more information.
The solution is to use a decimal-based data type, which exists in BigDecimal.

multiplying DecimalFormat number (no longer rounded properly)

I'm basically trying to use DecimalFormat to get to two decimal places. I'm taking two integer values then dividing them and casting to a double I've put in sample values below. When I do as below I get a value that is no longer to two decimal places. It seems to be when multiply by the 3 it loses it's rounding.
DecimalFormat df = new DecimalFormat("#.00");
double d = Double.parseDouble(df.format((double)5/6))*3;
System.out.println(d);
Can you let me know why this occurs and how to fix this?
In the statemet:
double d = Double.parseDouble(df.format((double)5/6))*3;
the formatting is not preserved (Double returns a double).
You could do, e.g.:
System.out.println(df.format(d));

Java, rounding a double to two decimal places

I'm trying to round a double to the nearest two decimal places however, it is just rounding to the nearest full number.
For example, 19634.0 instead of 19634.95.
This is the current code I use for the rounding
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;
I can't see where i am going wrong.
Many thanks for any help.
Well, Math.round(Math.PI*Radius()*Radius()*100) is long. 100 is int.
So Math.round(Math.PI*Radius()*Radius()*100) / 100 will become long (19634).
Change it to Math.round(Math.PI*Radius()*Radius()*100) / 100.0. 100.0 is double, and the result will also be double (19634.95).
You can use a DecimalFormat object:
DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);
System.out.println (df.format (19634.95));
Do you actually want want to round the value to 2 places, which will cause snowballing rounding errors in your code, or simply display the number with 2 decimal places? Check out String.format(). Complex but very powerful.
You might want to take a look at the DecimalFormat class.
double x = 4.654;
DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());
This gives "x=4.65". The difference between # and 0 in the pattern is that the zeros are always displayed and # will not if the last ones are 0.
The following example came from this forum, but seems to be what you are looking for.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}

Print Integer with 2 decimal places in Java

in my code i use integers multiplied by 100 as decimals (0.1 is 10 etc). Can you help me to format output to show it as decimal?
int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));
I would say to use 0.00 as format:
int myNumber = 10;
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(format.format(myNumber));
It will print like: 
         
10.00
The advantage here is:
If you do like:
double myNumber = .1;
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(format.format(myNumber));
It will print like:
0.10
You can printout a decimal encoded as an integer by divising by their factor (as a double)
int i = 10; // represents 0.10
System.out.println(i / 100.0);
prints
0.1
If you need to always show two decimal places you can use
System.out.printf("%.2f", i / 100.0);
Based on another answer, using BigDecimal, this also works:
BigDecimal v = BigDecimal.valueOf(10,2);
System.out.println(v.toString());
System.out.println(v.toPlainString());
System.out.println(String.format("%.2f", v));
System.out.printf("%.2f\n",v);
Or even your good old DecimalFormat will work with BigDecimal:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(v));
You can try this:-
new DecimalFormat("0.00######");
or
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
you can use double instate of int.
it gives you a output with decimals.
and then you can divide with 100.
you can use double instate of int.
it gives you a output with decimals.
if you want the number to stand behind the dot. you can use this:
**int number=100;
double result;
result=number/(number.length-1);**
I hope you can you use this.

Truncate a float and a double in java [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 1 year ago.
I want to truncate a float and a double value in java.
Following are my requirements:
1. if i have 12.49688f, it should be printed as 12.49 without rounding off
2. if it is 12.456 in double, it should be printed as 12.45 without rounding off
3. In any case if the value is like 12.0, it should be printed as 12 only.
condition 3 is to be always kept in mind.It should be concurrent with truncating logic.
try this out-
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));
Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.
The expected result is:
12.49
12.45
12
double d = <some-value>;
System.out.println(String.format("%.2f", d - 0.005);
I have the same problem using Android, you can use instead:
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
but for this API Level 9 is required.
Another fast solution is:
double number = 12.43543542;
int aux = (int)(number*100);//1243
double result = aux/100d;//12.43
take a look with DecimalFormat() :
DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
Check java.math.BigDecimal.round(MathContext).
Try using DecimalFormat and set the RoundingMode to match what you need.

Categories