We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
So Does Java division round down? The answer is Yes. Java does a round down in case of division of two integer numbers.
Well this one works...
double roundOff = Math.round(a * 100.0) / 100.0;
Output is
123.14
Or as @Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
this will do it for you as well.
double d = 2.34568;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
String roundOffTo2DecPlaces(float val)
{
return String.format("%.2f", val);
}
BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
Go back to your code, and replace 100
by 100.00
and let me know if it works.
However, if you want to be formal, try this:
import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value);
double finalValue = (Double)df.parse(formate) ;
I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal
class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00")
or using Math.round(a * 100) / 100
.
import java.math.BigDecimal;
public class RoundingNumbers {
public static void main(String args[]){
double number = 123.13698;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
This program would give us below output
Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14
Try :
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff); }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With