How to round to 2 decimals during calculation in Java [duplicate] - java

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

Related

what is Double here? [duplicate]

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

Float/Double doesn't seem to be working. The result keeps coming out to be an integer [duplicate]

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.

How to print a number upto 4 decimal places without rounding off in java without using BigDecimal [duplicate]

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);

Java - even though the decimal number places below 5, be rouding up

I have this:
return ((Double) Math.ceil(Integer.parseInt(matcher.group()) / 10)).intValue();
I need a number even though the decimal number places below 5, be rouding up.
Using this code, I have these examples:
((Double) Math.ceil(14 / 10).intValue() = 1
((Double) Math.ceil(26 / 10).intValue() = 3
((Double) Math.ceil(25 / 10).intValue() = 3
I need:
((Double) Math.ceil(14 / 10).intValue() = 2
((Double) Math.ceil(26 / 10).intValue() = 3
((Double) Math.ceil(25 / 10).intValue() = 3
Dividing integers gives you integers. There is nothing for Math.ceil() to do, because the number you get isn't 1.4, it's 1. Convert at least one of your numbers to double before dividing:
e.g.
((Double) Math.ceil(Integer.parseInt(matcher.group()) / 10.)).intValue();
or
((Double) Math.ceil(Double.parseDouble(matcher.group()) / 10.)).intValue();
Change you int division to double division, for example as 14 / 10D.
Currently your 14/10 results in 1...
return (int) Math.ceil(Integer.parseInt(matcher.group()) / 10.0));
Also take care not to use integer division, 26/10 = 2.

How to round to 2 decimals in Java with floats [duplicate]

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.

Categories