division double android - java

I have a problem with my division on android:
double test= 100/ 1280;
double test2 = 0.2354;
System.out.println(test);
System.out.println(test2);
I have
0.0
0.2354
I'd like to have
0.078125
0.2345
Thanks

Try this
double test= (double) 100/ 1280;

if you specify one of the numbers in your division with a decimal, i.e.
double test = 100.0/1280;
It will give you the desired output.
The reason you are not getting the correct result, is that when dividing two ints, the resulting type will also be an int. In order to avoid this, you have to typecast one of the operands in the division to a double, or - as a shorter solution when you are explicitly setting the number in the operation and not using variables - you can add the ".0" to one of the numbers.

Related

- Rounding a double up & removing the numbers after a decimal point -

Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x will be 56. You can also use Math.ceil() and Math.floor() to round up or down respectively. Finally to make x a string use String.valueOf(). Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math class here and the String class here.
Use the Math.round() function. You can cast it to an int to eliminate the decimal places, or you can use Math.floor() or Math.ceil() to round it down or up before casting.
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x is the double:
String s = String.format("%.0f", x);

Issue in rounding a float to a precision

I am writing a function round:
static float round(float number, precision){}
The function should work like this: round(12.3456f, 3) = 12.345
My definition of function is like this:
public static float round(float value, int precision) {
float result;
if(precision <= 0){
throw new RuntimeException("Precision can not be zero or less");
}
int number = (int) power(10,precision);
value = value * number;
result = (float)Math.round(value)/number;
return result;
}
But the issue is that, my unit test case for this function doesn't pass,
public void mathTestNew() {
assertEquals("MathTest",12.341,OOTBFunctions.round(12.3416f,3));
}
The result is
junit.framework.AssertionFailedError: MathTest expected:<12.341> but was:<12.342>
I am not sure how to overcome this error. I am not sure if BigDecimal will help me in this.
Rounding normally occurs towards the nearest integer. So 12.3416 is correctly rounded to 12.342
If you want the rounding behaviour you seem to be asking for (where the number is rounded down towards negative infinity) then you should use Math.floor(x) instead of Math.round(x)
Also be careful with rounding floats / doubles as they both suffer from numerical inaccuracy. If you really want high accuracy on decimal places, you may be better using BigDecimal instead.
Math.round is "round-to-nearest". You probably want Math.floor.
If you did want to use BigDecimal:
public static float round(float value, int precision) {
if (precision <= 0) {
throw new IllegalArgumentException("Precision cannot be zero or less.");
}
BigDecimal decimal = BigDecimal.valueOf(value);
return decimal.setScale(precision, RoundingMode.FLOOR).floatValue();
}
You may lose accuracy when converting from BigDecimal to float, so if accuracy is a must, do not convert; keep the value as a BigDecimal.
As mentioned in other answers, float is an approximation of a base 10 number. The following demonstrates just that:
System.out.println(BigDecimal.valueOf(12.3416f)); // outputs 12.34160041809082
System.out.println(new BigDecimal("12.3416")); // outputs 12.3416
12.3416 rounded is 12.342. There in lies your problem. You probably want Math.Floor instead. I would recomend against constantly multiplying as that can ruin the number. However, by 10 does not lower precision.
You can't write such a method. Floating point doesn't have decimal places, it has binary places. Ergo you cannot round to a specified number of decimal places. If you want decimmal places you must use a decimal radix, i.e. BigDecimal, or DecimalFormat. Apart from the error in expectation noted by #ColeJohnson, code like you have written will fail in over 90% of cases.

Java math logic error

I have the following code in my project:
int percent = 2;
int count = 10;
int percentagefill = (percent/10)*count;
System.out.println(percentagefill);
Basically what is happening is that, I'm setting two variables, percent and count. I then calculate the percentage fill. For some strange reason the percentage fill is resulting in a 0, when in this case it should be 2. Any ideas why? Thanks in advance.
intdivided by int will still result in int. In this case:
(percent/10)*count
= (2/10)*10
= (0) * 10 <-- 0.2 is rounded down to 0
= 0
You can read this question for reference. Also, here's the Java spec where is says that integer division is rounded towards 0. As for the fix, as long as floating point precision does not become an issue, just use double as PaulP.R.O said.
You could divide by 10.0, or change int percent to double percent in order to force a conversion to double. Otherwise, you are getting integer division, which truncates off the decimal part.
Here is a relevant question: "Java Integer Division, How do you produce a double?"
if you really need the result to be an int, you could do the multiply before the divide to avoid the integer division giving you zero.
int percentagefill = (percent*count)/10;
Change this line:
int percentagefill = (percent/10)*count;
To:
double percentagefill = (percent/10.0)*count;
This will use floating point arithmetic (because of the 10.0 instead of 10), and store the result in a double (which has precision past the decimal point unlike an int).
As others have mentioned, you're losing precision with integer division
The solution depends on your needs: if your result needs to be an integer anyway, multiply first:
int percentagefill = (percent*count)/10;
Could be "good enough" for you (you'll get the correct answer rounded down).
If you need to be able to get fractional answers, you need to convert things to floating point types:
double percentagefill = (percent/10.0)*count;
// ^ the .0 makes this a double,
// forcing the division to be a
// floating-point operation.
It's easy to fix:
int percent = 2;
int count = 10;
double percentagefill = (percent/10.0)*count;
System.out.println(percentagefill);
Dave Newton, your answer should have been an answer. :)
The integer 2 / the integer 10 = 0.
The integer 0 * the integer 10 = 0.
You will need a float or double data type. While working with information, always be weary of chances for the interpreter to make data type assumptions and "casts". println takes an intefer and casts to a string for display is one example.
Most of my work is in php and when working with values, 0, NULL, ERROR can all be different things and can yield unexpected results. Sometimes you may need to explicitly cast a variable to a different data type to get the intended results.
This is so due to the fact that you are using the integer data type when you should be using a floating-point data type such as double. This code should result in 2.0:
double percent = 2;
double count = 10;
double percentagefill = (percent/10)*count;
System.out.println(percentagefill);

Float.doubleValue() method

I'm searching for the best practice to convert Float to Double without loosing precision. So far I only found that a proper way to do so is to convert the Float to String and the String to Double.
Searching the Float API I stumbled upon this method doubleValue(). I thought this is a static constructor that will return a double from my Float without loosing precision but the following code behaves like a cast:
public class Main {
public static void main(String[] args) {
Float floatNumber= 4.95f;
Double doubleNumber= floatNumber.doubleValue();
System.out.println(doubleNumber);
}
}
The output is 4.949999809265137
Searching any other documentation about this from the Float API I didn't find any documentation to tell me what exactly happens when I call that method. Does anybody have any idea? Or can someone confirm that all the method does is perform a cast my Float to a double and unbox it?
The simple primitive-type cast (or even an implicit conversion) will do all you need, if you really want to preserve the value of a float:
float f = 4.95f;
double d = f;
Fundamentally 4.95f is already inaccurate - you can't represent that number exactly as a float. The exact value of floatNumber is represented in doubleNumber too - it's just that that value is not 4.95.
If you really care about the exact decimal digits, you should be using BigDecimal instead (or a scaled integer).
Widening float to double conversion doesn't lose precision in java.
When you use floating point, you get rounding errors which can be potentially "corrected" by rounding the result (assuming you know the precision you want). BigDecimal handles this by always knowing the precision.
float floatNumber= 4.95f;
double doubleNumber = (double) floatNumber;
System.out.println("After cast " + doubleNumber);
System.out.printf("Show two decimal places. %.2f%n", doubleNumber);
doubleNumber = Math.round(doubleNumber * 100) / 100.0;
System.out.println("After rounding to two places " + doubleNumber);
prints
After cast 4.949999809265137
Show two decimal places. 4.95
After rounding to two places 4.95

Converting double to integer in Java

In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.
is there a possibility that casting a double created via Math.round() will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.

Categories

Resources