Dividing two ints into a big decimal [duplicate] - java

This question already has answers here:
ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"
(9 answers)
Closed 7 years ago.
I'm conducting an experiment in which we will occasionally have to divide small numbers by large numbers, for example: 4 / 90,000. Using a double results in a 4.444444444e. I was hoping perhaps a BigDecimal could handle this arithmetic and give me a meaningful decimal, but my implementation throws an error:
int count = 4;
int total = 90,000;
er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total));
Error is:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
Update: I am interesting in atleast 3 decimal places of precision.

You could pass a MathContext to the division method call. Something like,
int count = 4;
int total = 90000;
BigDecimal er = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(total),
MathContext.DECIMAL128);
System.out.println(er);
And I get
0.00004444444444444444444444444444444444

Related

Take the decimal part of a double/float number [duplicate]

This question already has answers here:
How do I get whole and fractional parts from double in JSP/Java?
(18 answers)
Closed 4 years ago.
I have a simple question, I want to know how can I get the decimal part from a double/float number without the dot.
Example: a=0.75 and b=3231.0131
So I would like to set those decimal values in two new Integer variables: m=75 and b=0131.
I'm going to clarify some things, I want to create a new int variable, that variable will storage the decimal part from the original number.
double a = 0.75
double b = 12.033
int x = decimalofa
int y = decimalofb
System.out.println("the decimal of"+a+"is"+x+"and the decimal of"+b+"is"+y)
//the decimal of 0.75 is 75 and the decimal of 12.033 is 033
The thing is that i'm not sure if 033 could be considered as an integer number, so in other words I just want to take all the numbers next to the point and save them in a new variable.
Just do
float a = 0.75f;
System.out.println(Float.toString(a).split("[.]")[1]);
This only works if there is a decimal and there are numbers after that decimal

Dividing float by double vs dividing double by double in java [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
When I tried the following codes in Java:
System.out.println("0.1d/0.3d is " + 0.1d/0.3d)
System.out.println("0.1f/0.3d is " + 0.1f/0.3d)
I get the following output:
0.1d/0.3d is 0.33333333333333337
0.1f/0.3d is 0.3333333383003871
If float/double should get a double then float/double should be same with double/double in this case.
Just execute the below code to see binary string of number you want to check for:
System.out.println(Long.toBinaryString(Double.doubleToLongBits(0.1d)));
System.out.println(Integer.toBinaryString(Float.floatToIntBits(0.1f)));
Output:
11111110111001100110011001100110011001100110011001100110011010
111101110011001100110011001101
And you see the difference in float bits and double bits. so we can't get the same result for float/double and double/double for a longer precision values .
yes "milbrandt" said right when we are converting float quantity into double by implicit typecasting some information at decimal point will differ. That's why it is showing the different result while dividing float/ double.
As you probably know, double uses 64 bits to store a value but float 32 bits.
To represent significand, double uses 52 bits, and float uses 23 bits. Thus double can give 15 digit precision at most, and float can give 7.
If you do float / double, you actually try to divide a floating point with 7 digit precision at most (far to exact) by a floating point with 15 digit precision at most (closer to exact), and then implicitly typecast the result to a floating point with 15 digit precision. The typecast cannot restore your result from 7 digit precision to 15 digit. Therefore, the results are different though both of them are double.
initialize a double with a float and divide then. You will see the same result.
double f = 0.1f;
double d = 0.1d;
double n = 0.3d;
System.out.println("float /double = " + f/n);
System.out.println("double/double = " + d/n);
result is
float /double = 0.3333333383003871
double/double = 0.33333333333333337
The reason why you see this difference is because you don't have these exact values.
Even if we suppose 0.1d and 0.3d would be exact (which they aren't, what you can see on the result 0.33333333333333337), 0.1f is 0.10000000149011612, which makes the difference.

Java BigDecimal divide [duplicate]

This question already has answers here:
How can I divide properly using BigDecimal
(2 answers)
Closed 5 years ago.
What am I doing wrong here? Pretty sure this is right, I'm able to print the total, but then it breaks on calculating average.
public static void main(String[] args) {
BigDecimal test1 = new BigDecimal("67");
BigDecimal test2 = new BigDecimal("76");
BigDecimal test3 = new BigDecimal("99");
BigDecimal test_count = new BigDecimal("3");
BigDecimal total = test1.add(test2).add(test3);
System.out.println(total);
BigDecimal average = total.divide(test_count);
System.out.println(average);
}
Exception thrown:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1690)
at HelloWorld.main(HelloWorld.java:31)
The ArithmeticException is thrown because your division leads to a non terminating decimal, if you explicitly provide the method with a rounding mode, this exception will no longer be thrown. So, try this
BigDecimal average = total.divide(test_count, RoundingMode.HALF_UP);

Best way to generate (random) a division which result is not a decimal number [duplicate]

This question already has an answer here:
Generate numbers that divide evenly [closed]
(1 answer)
Closed 6 years ago.
I have to create a method that generates randomly 2 numbers, that divided give as result a number without decimals.
For example:
int result = 4 / 2; //is ok
int result = 4 / 3; //is NOT ok
I already create a recursive method that, when the result is a decimal number, call itself and generates 2 new numbers. But, of course, this is not the best approach since, in theory, I may get as a result a decimal number forever!
Is there a good way to achieve my goal?
Why not generate the result and divisor, then multiply both to get the dividend?
Instead of using 4 and 3 as dividend and divisor, which results in a decimal number when divided, multiply them both to get 12 as dividend and 4 as divisor which once divided gives 3.
when numerator/denominator = result, then numerator= result x denominator
then it will be easier to gen result and denominator :)
int numerator;
int denominator;
int result;
result= rand.nextInt(5,10);
denominator= rand.nextInt(2,10);
numerator = result * denominator;

Round number with Math round: doesn't work [duplicate]

This question already has answers here:
Round number to only first decimal place
(3 answers)
Closed 8 years ago.
I wish I could understand how it is possible that is not rounded the decimal number obtained from the following code.
File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize2 = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
double result = availableBlocks * blockSize;
free = (Preference)this.findPreference("free_mem");
free.setSummary(Double.toString(result)+" GB");
In a code similar to this use this instruction and works
result = Math.round(result * 10) / 10d;
Why not work here and I still see a number with many decimal places?
If I understood your question right you need NumberFormat here:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(result);
This produces a number with 1 decimal places.
So if result is 6.6789 it will produce 6.7.
Related: Round number to only first decimal place
Just a note:
If you do this:
Math.round(result * 10) / 10d;
you basically say:
Multiply result with 10
Round the result
Then divide with ten.
When you got rid of the decimals at step 2. you got another bunch of decimals after the division.

Categories

Resources