Java Double/Integer - java

int a = 1;
int b = 10;
int c = 3;
int d = (1/10)*3
System.out.println(d)
Result: 0
How do i make this Calculation work ?
and round up or down ?
It should be:
(1/10)*3 = 0.1 * 3 = 0.3 = 0 and
(4/10)*3 = 0.4 * 3 = 1.2 = 1
Thanks a lot!

1 / 10
This is integer division and as integer division the result is 0.
Then 0 * 3 = 0
You can use double literals:
1.0 / 10.0

Try:
int d = (int) (((double)4/10)*3);

1/10
This line return 0.so 0*3=0.Use double instead of int

as both a and b are integer so the output will also be int which makes 1/10 as 0 and then 0*3=0

You will want to perform the calculation using floating-point representation. Then you can cast the result back to an integer.

I note that you refer in your question to rounding up/down.
Math.round() will help you here.
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.

This will works
int a = 1;
int b = 10;
int c = 3;
int d = (1*3/10);
System.out.println(d);

Related

How can I get only the decimal value of a number and I will store that value into another variable using Java? [duplicate]

I have a double variable d = 1.15.
I want the number after the decimal point, i.e. "15".
What is best way to achieve this in Java?
I have tried like this:
Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));
But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.
Try this:
String numberD = String.valueOf(d);
numberD = numberD.substring(numberD.indexOf("."));
Now this numberD variable will have value of 15
Try Math.floor();
double d = 4.24;
System.out.println( d - Math.floor( d ));
To prevent rounding errors you could convert them to BigDecimal
double d = 4.24;
BigDecimal bd = new BigDecimal( d - Math.floor( d ));
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.toString() );
Prints 0.2400
Note that the 4 in setScale is the number of digits after the decimal separator ('.')
To have the remainder as an integer value you could modify this to
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
Prints 24
The number after the decimal point is not a well defined concept. For example for "4.24", it could be "0.24", "0.239999999999" (or similar), "24" or "239999999999".
You need to be clear if you are talking about a number or a string of decimal digits ... and whether the input value is a representation of a binary floating point number (in which case "4.24" is most likely an approximation) a decimal floating point number.
Depending on your interpretation, the correct answer will be different.
But i didn't get the proper answer because when I converted d.toString() the answer is 14.999999999999986.
You are running up against the problem that double and float are base-2 floating point formats, and in most cases they CANNOT represent decimal floating point numbers precisely. There is no fix for this ... apart from using something like BigDecimal to represent your numbers. (And even then, some loss of precision is possible whenever you do a division or modulo operation.)
Try out RegEx, here ^\d*\., will search for digits followed by dot and replace with blank.
for(double d : new double[]{1.15,0.009,222.9,3.67434}){
System.out.println(String.valueOf(d).replaceAll("^\\d*\\.",""));
}
gives:
15
009
9
67434
If you want the decimal places and you want to round the result.
double d = 4.24;
System.out.printf("%0.2f%n", d - (long) d);
prints
0.24
If you want a rounded value, you have to determine what precision you want.
double d = 4.24;
double fract = d - (long) d;
fract = (long) (fract * 1e9 + 0.5) / 1e9; // round to the 9 decimal places.
If your double is:
d = 1.25;
And if you do this:
String number = String.valueOf(d);
number = number.substring(number.indexOf(".")).substring(1);
then number will be 25.
I don't know if this is the best way to do this, but it works.
Have you tried d = d%1.0? That should return the remainder of dividing d by 1, which should just be the decimal portion.
You could also do this to get the value as an int: d = (int)((d%1.0)*100)
Instead of d.toString(), try this:
String str = String.format("%.2f", d);
Just as in any other language: multiply by 10 and check the int part of remnant when dividing by 10. The same way you would extract digits from an integer.
short[] digits = new short[max_len];
double tmp = d - ((int) d);
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digit[i] = (short) tmp;
tmp -= (int) tmp;
}
But be aware that for double you need to introduce a precision limit - the maximum number of digits to extract (max_len from the code sample above).
Slight update (added rounding at the edge of precision):
double d = 1.15;
short[] digits = new short[10];
double tmp = d - ((int) d) + 0.5 * 1e-10;
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digits[i] = (short) tmp;
tmp -= (int) tmp;
}
double d = 4.24;
d = (d - Math.floor( d ));
int e = (int)(Math.round(d*100));
System.out.println(e);
Yields 24
Scanner scr= new Scanner (System.in);
double d= scr.nextDouble();
BigDecimal bc= new BigDecimal ((d - Math.floor(d))*1e5);
bc=bc.setScale(4,RoundingMode.HALF_DOWN);
double f = bc.doubleValue();
while(f%10==0)
{
f=f/10;
}
System.out.println(f);
try this :
double d = 1.1512;
int i = (int) (d*100 - Math.floor(d)*100);
now this will give you : 15
ExAMPLE :
Double d = 469.951479;
String string = d.toString();
char[] len = string.substring(string.indexOf(".")).toCharArray();
System.out.println(len);
double myNumber = 1.15;
//numbers After Dot
double n = 2;
double right_of_dot = (myNumber - (int) myNumber)*Math.pow(10,n);
Try this:
var decimalsOnly = (parseFloat(decNum)-parseInt(decNum,10)).toFoxed(2);

Java - How to do floor division?

I know that in Python you can do floor division like this:
5 // 2 #2
The // is used for something totally different in Java. Is there any way to do floor division in Java?
You can do
double val = 5 / 2;
int answer = Math.floor(val);
OR
int answer = Math.floorDiv(5, 2);
If you were to call System.out.println(answer); the output would be
2
You can easily use Math.floorDiv() method.
For example:
int a = 15, b = 2;
System.out.println(Math.floorDiv(a, b));
// Expected output: 7
If you're using integers in the division and you cast the solution to another integer (by storing the result in another integer variable), the division is already a floor division:
int a = 5;
int b = 2;
int c = 5/2;
System.out.println(c);
>> 2
As khelwood stated, it also works with negative values but the rounding is done towards 0. For example, -1.7 would be rounded to -1.
use floorDiv()
int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));

Java: Convert floating point decimal number to the power of to integer

So I have the following number
3.454545E5
Notice the "E" letter which indicates to the power of
Is there a way to conver this number to
3454545
?
double d = 3.454545E5;
int i = (int) d;
Output: 345454.
If you want exactly 3454545:
int i = (int) (d*10);
You can use DecimalFormat to format the number any way you want.
If it is a string, first parse it as a double.
double yourNumber = 3.454545E5;
String output = String.format("%d", yourNumber);
try this
long l = (long) 3.454545E5;
Not sure if I understand you correctly but looks like you're interested in extracting mantissa from the number and dropping the exponent
This should work for you:
double number = 3.454545E5;
int exponent = (int)Math.log10(Math.abs(number)); // exponent = 5
double mantissa = number / Math.pow(10, exponent); // mantisa = 3.454545
To get your number you can multiply mantissa, in your particular example:
int result = (int)(mantissa * 1000000)
//result = 3454545
Can you try doing this?
double num = 3.454545E5;
int num1 = (int)num;
System.out.println(num1);
Here is the result -
345454

How do I get the part after the decimal point in Java?

I have a double variable d = 1.15.
I want the number after the decimal point, i.e. "15".
What is best way to achieve this in Java?
I have tried like this:
Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));
But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.
Try this:
String numberD = String.valueOf(d);
numberD = numberD.substring(numberD.indexOf("."));
Now this numberD variable will have value of 15
Try Math.floor();
double d = 4.24;
System.out.println( d - Math.floor( d ));
To prevent rounding errors you could convert them to BigDecimal
double d = 4.24;
BigDecimal bd = new BigDecimal( d - Math.floor( d ));
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.toString() );
Prints 0.2400
Note that the 4 in setScale is the number of digits after the decimal separator ('.')
To have the remainder as an integer value you could modify this to
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
Prints 24
The number after the decimal point is not a well defined concept. For example for "4.24", it could be "0.24", "0.239999999999" (or similar), "24" or "239999999999".
You need to be clear if you are talking about a number or a string of decimal digits ... and whether the input value is a representation of a binary floating point number (in which case "4.24" is most likely an approximation) a decimal floating point number.
Depending on your interpretation, the correct answer will be different.
But i didn't get the proper answer because when I converted d.toString() the answer is 14.999999999999986.
You are running up against the problem that double and float are base-2 floating point formats, and in most cases they CANNOT represent decimal floating point numbers precisely. There is no fix for this ... apart from using something like BigDecimal to represent your numbers. (And even then, some loss of precision is possible whenever you do a division or modulo operation.)
Try out RegEx, here ^\d*\., will search for digits followed by dot and replace with blank.
for(double d : new double[]{1.15,0.009,222.9,3.67434}){
System.out.println(String.valueOf(d).replaceAll("^\\d*\\.",""));
}
gives:
15
009
9
67434
If you want the decimal places and you want to round the result.
double d = 4.24;
System.out.printf("%0.2f%n", d - (long) d);
prints
0.24
If you want a rounded value, you have to determine what precision you want.
double d = 4.24;
double fract = d - (long) d;
fract = (long) (fract * 1e9 + 0.5) / 1e9; // round to the 9 decimal places.
If your double is:
d = 1.25;
And if you do this:
String number = String.valueOf(d);
number = number.substring(number.indexOf(".")).substring(1);
then number will be 25.
I don't know if this is the best way to do this, but it works.
Have you tried d = d%1.0? That should return the remainder of dividing d by 1, which should just be the decimal portion.
You could also do this to get the value as an int: d = (int)((d%1.0)*100)
Instead of d.toString(), try this:
String str = String.format("%.2f", d);
Just as in any other language: multiply by 10 and check the int part of remnant when dividing by 10. The same way you would extract digits from an integer.
short[] digits = new short[max_len];
double tmp = d - ((int) d);
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digit[i] = (short) tmp;
tmp -= (int) tmp;
}
But be aware that for double you need to introduce a precision limit - the maximum number of digits to extract (max_len from the code sample above).
Slight update (added rounding at the edge of precision):
double d = 1.15;
short[] digits = new short[10];
double tmp = d - ((int) d) + 0.5 * 1e-10;
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digits[i] = (short) tmp;
tmp -= (int) tmp;
}
double d = 4.24;
d = (d - Math.floor( d ));
int e = (int)(Math.round(d*100));
System.out.println(e);
Yields 24
Scanner scr= new Scanner (System.in);
double d= scr.nextDouble();
BigDecimal bc= new BigDecimal ((d - Math.floor(d))*1e5);
bc=bc.setScale(4,RoundingMode.HALF_DOWN);
double f = bc.doubleValue();
while(f%10==0)
{
f=f/10;
}
System.out.println(f);
try this :
double d = 1.1512;
int i = (int) (d*100 - Math.floor(d)*100);
now this will give you : 15
ExAMPLE :
Double d = 469.951479;
String string = d.toString();
char[] len = string.substring(string.indexOf(".")).toCharArray();
System.out.println(len);
double myNumber = 1.15;
//numbers After Dot
double n = 2;
double right_of_dot = (myNumber - (int) myNumber)*Math.pow(10,n);
Try this:
var decimalsOnly = (parseFloat(decNum)-parseInt(decNum,10)).toFoxed(2);

How to cast a double to an int in Java by rounding it down?

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.

Categories

Resources