get value after decimal point in java with precision - java

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?

Related

Division and Modulo-Division of a double value to get integer value as the result [duplicate]

I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (#Chris Wong)
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8) and (int)(1.2), which will both "round down" towards 0 and return 1), simply add 0.5 to the double that you will typecast to an int.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1 and y = 1):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1 and y = 2):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double is rounded up or down upon (int) typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1 whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int) typecasting, but 10.23 and 10.7 will be rounded up to 11.
(int)99.99999
It will be 99.
Casting a double to an int does not round, it'll discard the fraction part.
Math.floor(n)
where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.
This works fine int i = (int) dbl;
new Double(99.9999).intValue()
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
Try using Math.floor.
In this question:
1.Casting double to integer is very easy task.
2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:
double d=99.99999999;
int i=(int)d;
System.out.println(i);
and it will print 99, but rounding hasn't been done.
Thus for rounding we can use,
double d=99.99999999;
System.out.println( Math.round(d));
This will print the output of 100.

Java / Android - equation for rounding up

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.

Float to big decimal

I have to write a program with the following requirements:
I have a variable of type float, say float a = 3333.333f;
I have a variable of type int, say int b = 9999;
When I perform a*b in calculator, the result will be 33329996.667
After rounding up the decimals to 2 places, I want to print the value as 33329996.67 in java. I tried with long, double, float, big decimal, But couldnt succeed.
Can anyone please help me solving this?
float only has 7 digits of precision, so its not a good choice for a result with more than 7 digits. double has up to 16 digits of accuracy and is a better choice.
double a = 3333.333;
int b = 9999;
System.out.printf("%.2f", a * b);
prints
33329996.67
To determine the number of digits after the comma you have to apply a little trick:
First shift the comma to the right for the amount of digits you want to have, then cut the whole number e.g. with Math.ceil(float f) and then shift the comma back to the left.
That will illustrate that:
float f = 33329996.667;
float f2 = Math.ceil((f * 100)) / 100;
f2 now has the value 33329996.67.
Hope this helps.
EDIT: For formatting have a look here

Given 35 / 4, I want an "8" returned

Rather than an "8.75" returned.
Which method? Thanks.
If I'm not completely wrong, 35/4 always evaluates to 8. Even in
double result = 35 / 4;
you will get this result (as double, i.e. 8.0). This is because 35 and 4 are both integers and therefore integer division is applied. The expression is first evaluated as integer and only the result is cast to a double value.
On the other hand, if you want the correct result 8.75 you' ll have to write
double result = 35. / 4;
in order to force floating point division to be applied. This is a common pitfall by the way.
Of course, if you have double values, like in
double a = 35;
double b = 4;
you need to either explicitely cast to an int or use Math.floor() as suggested in previous posts.
Use
Math.floor(..)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
Or, if you need to manipulate ints, not doubles, then simply assign to int:
int a = 35 / 4;
Actually, if you work with the numbers directly, or with int variables, you will get an int result automatically.
cast to int
(int)
example :
http://www.javaprogrammingforums.com/java-code-snippets-tutorials/314-how-type-cast-convert-double-integer.html
explicitly cast the expression as int
int x = 35/4
integer division causes 8 to be returned instead of 8.75
using
int myInt = (int) Math.floor(value);
8.75 will be rounded to 8. Casting to int removes decimals in case value is a double.

Java using Mod floats

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.

Categories