Strange rounding issue with BigDecimal [duplicate] - java

This question already has answers here:
BigDecimal adding wrong value
(5 answers)
BigDecimal Method returns vague results, why does this happen?
(2 answers)
Closed 3 years ago.
Note this is not a duplicate, I'm and referring to rounding; not adding.
So I am dealing with BigDecimal and everything I do works as planned except for the rounding of certain numbers. It is easier to explain with code, but the rounding changes property between numbers. Note this is a always round down mode (truncating). It should round to 6 numbers in the decimal point.
System.out.println( (new BigDecimal(1.340)).round(new MathContext(7, RoundingMode.DOWN))); //returns 1.400000
System.out.println( (new BigDecimal(2.340)).round(new MathContext(7, RoundingMode.DOWN))); //returns 2.339999
I understand BigDecimal, rounding, etc. What is strange is simply changing the first number from 1 to 2, 3, 4, 5, ... n makes the value n.339999.
In other words, for n.340 where n > 1, rounding in this form gives n.339999 while if n = 1, it yields, 1.400000
What am I doing wrong? How can I fix this problem and make it the 1.400000 version? It is preferable to use this format because everything else I am dealing with (unnecessary to this question) works in this format where it is rounded in this way.

Don't initialize your BigDecimal with a double. You already have a precision problem when you create your BigDecimal. Use a String instead:
System.out.println( (new BigDecimal("1.340")).round(new MathContext(7, RoundingMode.DOWN))); //returns 1.340
System.out.println( (new BigDecimal("2.340")).round(new MathContext(7, RoundingMode.DOWN))); //returns 2.340

Related

How to round numbers to four decimal place in Java? [duplicate]

This question already has answers here:
How to print a float with 2 decimal places in Java?
(18 answers)
Closed 7 years ago.
So let's say I have a simple array of float numbers
[0.315023, 1.0, 0.12345, 0121111]
And call it arr1.
I need to take this array and turn it into this:
[0.3150, 1.0000, 0.1234, 0.1211] *Please note that 1.0 is now 1.0000 and 0.3150 has a 0 at the end
I have tried using a for loop to iterate through the array and rounding the numbers as follows:
// i representing a number in the arr1; let's imagine that "newNum" replace the original numbers in arr1
float newNum = Math.round(i*10000.0000)/10000.0000;
What will result is following:
[0.315, 1.0, 0.1234, 0.1211]
As you can see, the first item is missing the 0 at the end, and the second item is missing a lot of zeros at the end.
I have tried to use DecimalFormat, but it doesn't work with the float array; also I am not trying to format decimals, I am rounding them. (although I have tried the round first then format second; which didn't work because of difference in datatype).
PLEASE for the love of God, help me. This is like the last thing I need to complete for my project. I am so close! Thank you so much in advance!
*PS: I need to make sure the array remains FLOAT; I need to use the data in the array later on.
DecimalFormat f = new DecimalFormat("##.0000");
System.out.println(" output : "+ f.format(2.56));
Follows java docs for format data
Use this:-
DecimalFormat twoDForm = new DecimalFormat("#.####");
double d = Double.valueOf(twoDForm.format(newNum));

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.

How to display decimal numbers in Java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I'm using float to display decimal numbers, but sometimes it doesn't display correct result.
For example, for 6.2/1000 the result is 0.0061999997.
I know why is this happening, but I wonder is there a way to display correct result, in this case, 0.0062?
EDIT:
How to round a number to n decimal places in Java does not answer to my question, so why did you marked my question as already been answered in other place?
Numbers I wrote are only example. In the app user can enter any number and divide / multiply number with any other number, so the result maybe won't have any decimal points, maybe it will have 4 decimals, maybe it will have 7 decimals,...
First, you need to understand that this isn't just a display issue - if you want to avoid displaying incorrect values, it helps to have the right values to start with.
You should use BigDecimal instead of float. That stores the value as an integer scaled by a factor of 10exp rather than the 2exp used by double and float.
If the BigDecimal.toString doesn't format the result the way you want, use DecimalFormat to perform the formatting instead.
Format the decimal places use this:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(decimalPlace);
String formatedValue = df.format(value);
Hope this will resolve your query.

Why does this Java division print out zero? [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
I have the following line of code:
System.out.println(5/9);
I expect to see 0.555 as a result, but instead it prints out zero. Can someone help me understand why this happens? I am currently learning programming and appreciate the help.
Thanks!
This happens because what you are unknowingly doing is Integer Division.
To make calculations fast, computer uses Integer division method when there's no decimal number involved, and hence decimal values are lost.
Try this out:
System.out.println(5.0 / 9.0);
or
System.out.println(5.0 / 9);
or
System.out.println(5 / 9.0);
or
System.out.println((float) 5 / 9);
or
System.out.println(5 / (float) 9);
You trying to divide 5 by 9.Both are integers.So the answer is also an integer.So return 0 as answer.So try like System.out.println(5.0/9); or assign values to float variables and go with that
Integer divide by Integer returns Integer
Do like this
System.out.println(5.0/9);
This is an integer division because both operands are of type integer. An integer division gives an integer result obtained by truncation.
When Integer division is ran in Java (Integer / Integer), the number is calculated then rounded down to the while number. Therefore, 5/9 is evaluated as 0.55555 then rounded down to 0.

division problems [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
This line of code:
System.out.println ("array[j], "+array[j]+", divided by sum, "+sum+", equals: array[j]/sum: "+ array[j]/sum) ;
is yeilding this line of text:
array[j], 21, divided by sum, 100, equals: array[j]/sum: 0
why is it doing this? (everything is right eccept that the answer should be .21)
Are you sure that your array is not integer ?
if it's, try using double.
I'm assuming that aray is an int[] and sum is an int. In this case, Java will perform integer division, which results in 0 in this case.
Others noted the cause. To fix, (double) aray[j]/sum.
Dividing integers will get you an integer answer rounded down to the first whole number. If you want a decimal result, you have to make it 21.0/100.0.

Categories

Resources