This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 1 year ago.
I understand double as a variable type but in line 4 it might be used as datatype conversion. I just don't get the double used in line 6, am I completely missing the point here?
public static void main(String args[]) {
int discountPercentage = 10;
double totalPrice = 800;
double priceAfterDiscount = totalPrice * (1 - ((double) discountPercentage / 100));
if (totalPrice > 500) {
priceAfterDiscount = priceAfterDiscount * (1 - ((double) 5 / 100));
}
System.out.println("Customer has paid a bill of amount: "+ priceAfterDiscount);
}
Writing 5 / 100 is an int division as both operand are ints, and in Java that will result in 0.
See Int division: Why is the result of 1/3 == 0?
To get 0.05, you need to make a division with double
define an operand as double explicitly
5.0 / 100
5 / 100.0
cast an operand
(double) 5 / 100
5 / (double) 100
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Integer division: How do you produce a double?
(11 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
final double PI = Math.PI;
final double sphereVolumeConstant = (4/3);
System.out.println("Volume of a sphere.");
System.out.print("Radius of sphere: ");
double radius = userInput.nextDouble();
double volumeOfSphere = sphereVolumeConstant * PI * Math.pow(radius, 3);
System.out.println("Volume = " + sphereVolumeConstant);
}
}
Terminal:
Volume of a sphere.
Radius of sphere: 5
Volume = 1.0
I am trying to calculate the constant itself which keeps coming out to be an integer even though it shouldn't, or at least I don't think it should. Can someone please help/explain?
sphereVolumeConstant will always be 1.0. writing double before variable doesn't make every operation on it double. If You want to make sphereVolumeConstant to be equal to 1.(3) You have to write:
final double sphereVolumeConstant = (4.0/3);
Or:
final double sphereVolumeConstant = ((double) 4 / 3);
Now the operation will be made in double because 4.0 or (double) 4 is double.
Because the value of sphereVolumeConstant is assigned as (4/3), its value will always be 1.0 because of how integer division works. What you need to do is cast at least the 4 or the 3 to a double/float:
final double sphereVolumeConstant = ((double)4/3);
final double sphereVolumeConstant = (4/(double)3);
final double sphereVolumeConstant = (4.0/3);
final double sphereVolumeConstant = (4/3.0);
This thread explains why integer division behaves in this way.
Default is int for your dividend & divisor
In your example ( 4 / 3 ), the 4 and the 3 (your dividend & divisor) both default to being integers. So you are dividing one integer by another. You get a resulting integer as your quotient.
System.out.println( 4 / 3 ) ;
1
Then you cast that resulting integer to be a double, 1.0.
double a = ( 4 / 3 )
1.0
If you mean 4 or 3 to be floating-point numbers, say so. Mark them with a d for double or f for float.
( 4d / 3d )
1.3333333333333333
Or use decimal separator.
( 4.0 / 3.0 )
1.3333333333333333
BigDecimal
If you care about accuracy rather than speed-of-execution, use BigDecimal. Never use float/Float or double/Double for money or other matters demanding accuracy.
Pass a MathContext containing precision (total number of digits) and RoundingMode.
MathContext mc = new MathContext( 7 , RoundingMode.HALF_EVEN ) ; // Banker's rounding.
BigDecimal d = new BigDecimal( "4" ).divide( new BigDecimal( "3" ) , mc ) ;
1.333333
Alternatively, pass scale (number of digits to the right of the decimal separator) and RoundingMode.
BigDecimal e = new BigDecimal( "4" ).divide( new BigDecimal( "3" ) , 2 , RoundingMode.HALF_EVEN ) ;
1.33
Example code
See all that code run live at IdeOne.com.
This question already has answers here:
How do I format double input in Java WITHOUT rounding it?
(3 answers)
Closed 4 years ago.
if input = 31.6227890
then output = 31.6227
but the output is coming as 31.6228
You can use below function:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public static double formatValue(Double number) {
DecimalFormat df = new DecimalFormat("####0.0000");
return Double.parseDouble(df.format(number));
}
Edit :
you have to add below code for rounding off.
df.setRoundingMode(RoundingMode.DOWN);
Input = 31.6227890
Output = 31.6227
If you want to round down, you can use truncation like this.
double d = 31.6227890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);
prints
31.6227
Note: this might print less than 4 digits. If you always want 4 you need to use formatting.
d = 31.60007890;
d = ((long) (d * 10000)) / 10000.0; // truncates down to 0
System.out.println(d);
System.out.printf("%.4f%n", d);
prints
31.6
31.6000
NOTE: For large values you wouldn't round them as this would result in an overflow.
private static final double WHOLE_NUMBER = 1L << 53;
public static double trunc4(double d) {
final double factor = 1e4;
return Math.abs(d) >= WHOLE_NUMBER / factor
? d
: ((long) (d * factor)) / factor;
}
The point at which you get an error is for numbers so large they are whole numbers anyway (due to the limits of the precision on double)
NOTE: If you used float the limit at which you would get a precision error is for much smaller values.
double d = 1024.00039999;
float f= (float) (long) (d * 10000) / 10000;
System.out.println(f);
prints
1024.0002
You can round down using a BigDecimal:
new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN)
That returns the desired result: 31.6227.
For a double, you can use .doubleValue():
new BigDecimal(31.6227890d).setScale(4, RoundingMode.DOWN).doubleValue()
float i=(float)((int) (31.6227890 *10000))/10000;
System.out.println(i);
You can multiply it per 1000, use Math.floor() and divide it per 1000
double a = 10.345665654;
double b = Math.floor(a * 10000) / 10000;
System.out.println(b);
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 5 years ago.
So, assuming, for some reason, floats are absolutely required in the programme one is creating despite the inaccuracy regarding decimal points, is there any method one can use to round them to 2 decimal places without converting them into doubles?
Try this:
public static float roundFloat(float number, int scale)
{
int pow = 10;
for (int i = 1; i < scale; ++i)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Solid and fast.
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 5 years ago.
For one calculation I need to round to 2 decimals during the calculation.
Relevant code:
count = 500;
price = 0.00077
pounds = 150,000
double value = ((350 - count) * price) * (pounds / 100);
To get the result I need, (350 - count) * price must round to 2 decimal places before doing the pounds / 100 so how might i round to 2 decimal places during a calculation?
In java you can round it some think like that
double roundOff = Math.round(a * 100.0) / 100.0;
in your case
Math.round(((350 - count) * price) * 100d) / 100d
This question already has answers here:
Best method to round up to the nearest 0.05 in java
(4 answers)
Closed 8 years ago.
How is this possible in Java?
I have a float and I'd like to round it to the nearest .5.
For example:
1.1 should round to 1.0
1.3 should round to 1.5
2.5 should round to 2.5
3.223920 should round to 3.0
EDIT: Also, I don't just want the string representation, I want an actual float to work with after that.
#SamiKorhonen said this in a comment:
Multiply by two, round and finally divide by two
So this is that code:
public static double roundToHalf(double d) {
return Math.round(d * 2) / 2.0;
}
public static void main(String[] args) {
double d1 = roundToHalf(1.1);
double d2 = roundToHalf(1.3);
double d3 = roundToHalf(2.5);
double d4 = roundToHalf(3.223920);
double d5 = roundToHalf(3);
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);
System.out.println(d5);
}
Output:
1.0
1.5
2.5
3.0
3.0
The general solution is
public static double roundToFraction(double x, long fraction) {
return (double) Math.round(x * fraction) / fraction;
}
In your case, you can do
double d = roundToFraction(x, 2);
to round to two decimal places
double d = roundToFraction(x, 100);
Although it is not that elegant, you could create your own Round function similarly to the following (it works for positive numbers, it needs some additions to support negatives):
public static double roundHalf(double number) {
double diff = number - (int)number;
if (diff < 0.25) return (int)number;
else if (diff < 0.75) return (int)number + 0.5;
else return (int)number + 1;
}