Round up double value in java [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 2 years ago.
I want to round up a double value in java. Always to round up the value in ispite that matematecally correct way, sometimes, is round down the value. For example:
value = 6.5817
I want to round up, keeping two decimals. So I need the value will be like this:
value = 6.59
The important thing here is always keep two decimals and always round up the second decimal if the value have more two decimals.
Have someone idea how I can to do this in java?

Since double values are inexact, e.g. it cannot store a number like 0.07 exactly, you need to use BigDecimal to help round up a double value, with the least probability of getting the wrong value.
To round to 2 decimals, use:
double value = 6.5817;
double roundedUp = BigDecimal.valueOf(value).setScale(2, RoundingMode.UP).doubleValue();
System.out.println(roundedUp); // prints 6.59
Note that this code prints 0.07 when value = 0.07, unlike e.g. Math.ceil(value * 100.0) / 100.0, which incorrectly prints 0.08.

Try the following:
double a = 6.5817;
Math.ceil(a * 100.0) / 100.0;

Related

Print float with more decimal points [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
I am experiencing a very strange behaviour when i am trying to print float number with more decimal points.
Float price = Float.valueOf("1602.72");
System.out.println(price); //prints 1602.72
outputValue = String.format("%.6f", price);
System.out.println(outputValue); //prints 1602.719971
I have also used below code but getting the same result
DecimalFormat df = new DecimalFormat("0.000000");
System.out.println(df.format(price)); //prints 1602.719971
I am expecting outputValue as 1602.720000 (6 digits after decimal with extra zeros)
A float is a binary representation of a number ( 1 / 2 ^^ ? )
like:
1/2^1 = 0.5,
1/2^2 = 0.25,
1/2^3 = 0.125,
1/2^4 = 0.0625, ...
The result renders from an addition of this binary numbers to find the closest match.
Never use floats or doubles for prices, floats and doubles are approximations, see: IEEE_754.
Have a look at BigDecimal instead.
Edit to be exact: use floats or doubles to represents decimals is an approximation.
That happens because floating point values are often imprecise for decimal fractions.
Basically, since floats are represented using negative powers of 2, some decimal values are very hard to represent accurately (e.g.: how do you write 0.3 as a sum of powers of two?).
You can try Float.valueOf("1602.720000") or Double.valueOf("1602.72") (better), but those will probably have the same issues.
Refer to this answer for a more detailed explanation.

How to round off fractional part in java [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I have to divide 495/116533, i tried using long and double; but it's returning 0.0;
Once if i able to capture that value (0.004247) then i can use round of methods;
Please help me how to capture complete value( which data type it supports?)
For 4 decimals do:
(double) (Math.round(value * 10000) / 10000)
The number of zeroes is how many decimals you want to round to.
Essentially what you need to do is to first multiply your number by a factor of X so that only the section you want to show is in front of the decimal place, then you can round it using the Math.round function. After that, just divide it back by X in order to put the decimal back in the right spot.

Using float and double for calculation, giving different results [duplicate]

This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Is floating point math broken?
(31 answers)
Closed 7 years ago.
I am working on a project where we are calculating prices of items with 8 places of decimal points.
But sometime calculation results are different.
I tried some samples but getting different calculation results:
public static void main(String[] args) {
double value1 = 0.999939f * 0.987792f;
double value2 = 0.999939 * 0.987792;
double value3 = (double)0.999939f * 0.987792f;
System.out.println("value 1 : "+ value1);
System.out.println("value 2: "+ value2);
System.out.println("value 3 : "+ value3);
}
Outputs are:
value 1 : 0.9877317547798157
value 2 : 0.9877317446880001
value 3 : 0.9877317839126931
These three are different results.
I am confused. Can anyone please clarify me what is happening here?
Thanks.
I went through some already answered, But I just want some ways where I can calculate with float and doubles only. otherwise I have to change many places. It will be painful.
Because of how floats and decimals are represented, the casts could be causing different results.
For: double value1 = 0.999939f * 0.987792f you are multiplying two floats and then casting it to a double. The resulting float representation is the one being converted to a double.
For: double value2 = 0.999939 * 0.987792; you are multiply two doubles and saving it in a double. This is time there is no casting so the representation never changes (ie. no potential data loss from change in data representation).
For: double value3 = (double)0.999939f * 0.987792f; you are multiplying a double that is casted from a float, times a float. Because of how the Java math works, that second float is probably also being casted to a double, so now you are multiplying two doubles that were once floats causing a third set of representations.
Because float and doubles have different precisions each of these will get a different result. For more info about floating point arithmetic, see here.
When you write a number with the "f" character, it is taken as float, meaning it is encoded with 32bits, whereas without it, it is a double, encoded with 64bits.
The more bits, the more accurately you will represent decimal numbers. This does not make a difference for number with few decimals, but in your case it is significant.
In conclusion, use exclusively double variables in your code.

How to round a double to the nearest 10th place [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
public double hypotenuse()
{
//return Math.hypot(leg, leg); //returns 7.0710678118654755
//return 0.1 * Math.floor(Math.hypot(leg, leg) * 10); //returns 7.0
//return 0.1 * Math.ceil(Math.hypot(leg, leg) * 10); //returns 7.1000000000000005
return 0.1 * Math.round(Math.hypot(leg, leg) * 10); //returns 7.1000000000000005
}
I am trying to round to the nearest 10th place, so this number should round up to 7.1. Why does this method work with Math.floor but not with Math.round? Does anyone have any insight?
Thanks,
Sky
In regards to your answer to yourself, you don't want to convert an object of type A to type B, operate on it, and then convert it back to type A. Not if you can do anything else.
The following does what you want it to do:
public double hypotenuse()
{
return Math.round(Math.hypot(leg, leg) * 10) / 10.0;
}
I'm not entirely sure why. It would take some digging into what this compiles down to at the assembly level.
The real problem is that each double in Java only has a limited number of bits to store its decimal portion. There are an infinite number of possible real numbers in real life. There is no way you can represent every single real number with only 64 bits. This is why you should avoid floating point calculations in banking apps and software that requires the number to be exact. Multiplying a few doubles together can introduce quite a significant error margin in the calculation. See this explanation on another SO answer, which does a great job of explaining this further.
If you really need it to be exact, use BigDecimal.
Nevermind, this is what I found that works.
public double hypotenuse()
{
double hypot = Math.hypot(leg, leg);
String str = String.format("%1.1f", hypot);
hypot = Double.valueOf(str);
return hypot;
}
If this is for JS:
The Math.round() function returns the value of a number rounded to the nearest integer.

Solving A math equation using Java [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
I have hit a snag in my program when this calculates I get result of 0.0
y = 1/6*Math.pow(x,3)+1/2*Math.pow(x,2)-1/3*x;
I have tried writing the equation in chunks so I can add the results up after calculation but the result just keeps ending up being 0.0 and I don't know why. Is this a syntactical error or is there a rule that I'm missing about java?.
When you divide two integers Java truncates the result to an integer. If you want a fractional result you need to use floating point numbers. 1/2 is 0; 1.0/2.0 is 0.5.
y = 1.0/6.0*Math.pow(x,3) + 1.0/2.0*Math.pow(x,2) - 1.0/3.0*x;
y = 1/6*Math.pow(x,3)+1/2*Math.pow(x,2)-1/3*x;
Here you are doing division of two integers, which would result in 0. Make one/both of the values to decimal (1.0/6.0 etc) and then try this. It should give the correct result. The reason is that, 1/6 will be corrected to the closest integer value, which is 0.

Categories

Resources