I am building an android application. In my app, i need to be able to round up a double (42.42 for example) and also get how much i added to the original number in order to round it up. My current code isn't working, and its outputting 0.. Anyway to fix this?
My current code:
float rounded = FloatMath.ceil(val);
double getDecimal = (val - FloatMath.floor(val))*100;
int noDecimal = (int) ((int) 100-getDecimal);
float toadd = (noDecimal/100);
In my code the "rounded" variable is the simpel rounding, and "toadd" should be how much i added to it. For some reason toadd always comes back as 0. Any help?
You're dividing noDecimal by 100. Both are ints, and the result will always be an int. In this case, it's an int between 0 and 1, which will always be truncated to 0.
What's wrong with just getting the number modulo 1 (%1), then getting the ceiling of the original number?
For completeness, you could simply change the last line to preserve the rest of the logic:
float toadd = noDecimal/100.0;
This changes the divisor to a float, and an int divided by a float yields a float.
float toadd = (noDecimal/100);
This will give you 0, as you are dividing smaller integer by larger one..
Try to do like this: -
float toadd = (Float.valueOf(noDecimal)/100);
Also, you don't need to do typecast twice in the below code: -
int noDecimal = (int) ((int) 100-getDecimal);
Just, outer cast is enough: -
int noDecimal = (int) (100-getDecimal);
Edit: - Also, you might want to use BigDecimal for this kind of problems..
Maybe I'm missing something or not getting your intention right, but if you just want to know what you added, why don't just use the difference?
float rounded = FloatMath.ceil(val);
float toadd = rounded-val;
Edit: As mentioned in the comments, this might not always give the absolutely accurate result. But it's the general idea which can be used with BigDecimal, which offers a higher precision.
Related
Let's say I have:
double x = 2.546;
I need a int that's equal to 5, how would I go about it?
You need to multiply by 10, then cast as an int, then apply %10 operation
One easy way to get rid of trailing decimals from a double is to cast it to an int. With some clever casting, we can do this:
double x = 2.546;
x-= (int)x;
x *= 10;
int y = (int) x;
We remove the 1's position (2) from x by subtracting (int) x which is 2, from x which is 2.546. Then we multiply x by 10 to get 5.46. Then by casting x to an int, we get 5. This would work in many other languages.
Can you do this?
int intVar = parseInt(x.toString().substring(indexOf('.')+1,1));
I haven't actually attempted that, so you may need to tweak. But that's the idea.
The basic idea is, convert to string, find the decimal point, get the next character after it, and convert it to int.
You may have to flesh it out a bit to handle exceptions. Like, what if there is no decimal point?
I'm making a basic calculator where you can plus, times, divide and minus as i was experimenting to see if it worked i noticed that instead of 5 divided by being equal to 1.25 it only displayed 1.
Here's the code i use to handle the math problems:
if (box.getSelectedItem().equals(divide)){
JOptionPane.showMessageDialog(null, Integer.parseInt(first.getText()) / Integer.parseInt(second.getText()), "Answer", -1);
main(args);
}
Is there code that displays the decimal points as well?
Since you are using Integer,it is happening.
Use Double to preserve decimals.
In your case,use
Double.parseDouble(first.getText()) / Double.parseDouble(second.getText())
Integer division will give you Integer. Try using Double or BigDecimal data type.
You need to do the casting
(double)parseInt(first.getText()) / (double)parseInt(second.getText())
Int/Int will give you an Integer. So you need to cast it to Double to get the result in decimal.
EDIT:
If you dont want to show decimal when the result is a whole number then you need to check it like this:
Double res = (double)parseInt(first.getText()) / (double)parseInt(second.getText())
Integer x;
if(res % 1 == 0)
{
x = (int)res
}
I have a line in my code much like below:
float rand = (float) Math.random();
Math.random() returns a double that is >=0.0 and <1.0. Unfortunately, the cast above may set rand to 1.0f if the double is too close to 1.0.
Is there a way to cast a double to a float in such a way that when no exact equal value can be found, it always rounds down to the next float value instead of to the nearest float value?
I'm not looking for advice on RNGs, nor work-arounds such as following up with if(rand == 1.0f) rand = 0.0f;. In my case, that solution is a satisfactory way to fix my problem, and it has already been implemented. I am just interest in finding out "proper" solution to this kind of number conversion.
If you only want to round when rand==1.0f, then I second #paxdiablo's answer. However, it sounds like you're okay with always rounding, and simply want to always round down. If so:
float rand = Math.nextDown((float)Math.random());
from the javadoc:
nextDown(float f)
Returns the floating-point value adjacent to f in the direction of negative infinity.
In response to your comment - good point. To avoid that problem, you could simply wrap the statement in a call to Math.abs(), which will have no affect except when the result of nextDown() is negative.
float rand = Math.abs(Math.nextDown((float)Math.random()));
The option I'd suggest would be to use double rather than float.
The only disadvantages I've ever found generally only come into play when you have a large number of them, in that the storage requirements are higher, and this doesn't appear to be the case here.
If you must use float, then the solution you've already tried is probably the best one available. It's a fundamental problem that loss of precision when converting double to float may give you 1.0f.
So coerce the float value to be in your desired range.
However, you don't have to pepper your code with if statements for this, simply provide a float random function that does the grunt work for you:
float frandom() {
float ret = 1.0f;
while (ret == 1.0f)
ret = (float) Math.random();
return ret;
}
or, as per your sample:
float frandom() {
float ret = (float) Math.random();
if (ret == 1.0f)
ret = 0.0f;
return ret;
}
then call it with:
float rand = frandom();
This would be the point where it would be nice for Java (and others) to have the Javascript ability to "inject" code into a type so that you could implement frandom() into the static Math arena. That way you could just use:
float rand = Math.frandom();
But, alas, this is not yet possible (as far as I know, short of recompiling the Java support libraries, which seems a bit of an overkill).
By the way, if you're looking for the maximum float value less than 1, it's 0.99999994 (an exponent multiplier of 2-1 with all mantissa bits set to 1), so you could use that instead of 0.0f in the frandom() function above.
This is gleaned from a handy little tool I wrote some time ago, one that's proven invaluable when fiddling about with IEEE754 floating point values.
I want to use a method that requires an int. This int is determined by a division potentially solved as a double. I need to perform this as neat and short as possible and I am wondering if I can count that the method will take the double directly casted as int and if this means a single truncation with no roundings.
Do I have to necessarily use Math static methods?
Could this give errors for non int parameter entries to subList?
Could someone provide any guidance about this?
List<Integer> b = null;
List<Integer> c = null;
int size = a.size();
b.addAll(a.subList(0, size / 2)); // To hold the first half
c.addAll(a.subList(size / 2, size)); // To hold the second half [and excess]
Thank you in advance for your help.
it will take the double casted to integer and will not round it, just disregard everything after the "."
so if the division of 9.8/2 is 4.9 then you'll get 4 for doing
int x = 9.8/2;
you don't need to use the Math static methods for devision and you won't get errors for the code you gave
to conclude, you can just run your code and see if the result is as you want it.
b.addAll(a.subList(0, size / 2));
should run without problem
What's wrong with b.addAll(a.subList(0, (int)(size / 2)));?
I am working on an exercise in Java. I am supposed to use / and % to extract digits from a number. The number would be something like 1349.9431. The output would be something like:
1349.9431
1349.943
1349.94
1349.9
I know this is a strange way to do but the lab exercise requires it.
Let's think about what you know. Let say you have the number 12345. What's the result of dividing 12345 by 10? What's the result of taking 12345 mod 10?
Now think about 0.12345. What's the result of multiplying that by 10? What's the result of that mod 10?
The key is in those answers.
if x is your number you should be able to do something like x - x%0.1 to get the 1349.9, then x - x%.0.01 to get 1349.94 and so on. I'm not sure though, doing mod on floats is kind of unusual to begin with, but I think it should work that way.
x - x%10 would definetly get you 1340 and x - x%100 = 1300 for sure.
Well the work will be done in background anyway, so why even bother, just print it.
float dv = 1349.9431f;
System.out.printf("%8.3f %8.2f %8.1f", dv, dv, dv);
Alternatively this could be archived with:
float dv = 1349.9431f;
System.out.println(String.format("%8.3f %8.2f %8.1f", dv, dv, dv));
This is a homework question so doing something the way you would actually do in the real world (i.e. using the format method of String as Margus did) isn't allowed. I can see three constraints on any answer given what is contained in your question (if these aren't actually constraints you need to reword your question!)
Must accept a float as an input (and, if possible, use floats exclusively)
Must use the remainder (%) and division (/) operator
Input float must be able to have four digits before and after the decimal point and still give the correct answer.
Constraint 1. is a total pain because you're going to hit your head on floating point precision quite easily if you have to use a number with four digits before and after the decimal point.
float inputNumber = 1234.5678f;
System.out.println(inputNumber % 0.1);
prints "0.06774902343743147"
casting the input float to a double casuses more headaches:
float one = 1234.5678f;
double two = (double) one;
prints "1234.5677490234375" (note: rounding off the answer will get you 1234.5677, which != 1234.5678)
To be honest, this had me really stumped, I spent way too much time trying to figure out how to get around the precision issue. I couldn't find a way to make this program work for 1234.5678f, but it does work for the asker's value of 1349.9431f.
float input = 1349.9431f;
float inputCopy = input;
int numberOfDecimalPoints = 0;
while(inputCopy != (int) inputCopy)
{
inputCopy = inputCopy * 10;
numberOfDecimalPoints++;
}
double inputDouble = (double) input;
double test = inputDouble * Math.pow(10, numberOfDecimalPoints);
long inputLong = Math.round(test);
System.out.println(input);
for(int divisor = 10; divisor < Math.pow(10, numberOfDecimalPoints); divisor = divisor * 10)
{
long printMe = inputLong - (inputLong % divisor);
System.out.println(printMe / Math.pow(10, numberOfDecimalPoints));
}
Of my three constraints, I've satisfied 1 (kind of), 2 but not 3 as it is highly value-dependent.
I'm very interested to see what other SO people can come up with. If the asker has parsed the instructions correctly, it's a very poor exercise, IMO.