This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I have a code here that calculate a rate for payment. It works however certain value will result in numerous number of decimal points. I want the result to be converted into only 2 decimal point. How do I do this? below is the attached code:
double rateConv=(((new Double(4.4) * transaction.getAmount())/100)+(transaction.getAmount()+new Double(0.30)));
System.out.println(rateConv);
transaction.setCurrencyPsy(rateConv);
transaction.setUserId(getLoginUserProfile().getUserId());
transaction.setTransType(WalletConstant.TRANS_DEPOSIT);
transaction.setIsApproved(false);
transaction.setCreateDate(new Date());
transaction.setIsCiTrans(false);
transDAO.save(transaction,getLoginUserProfile(),getText("email.admin"));
if(transaction.getDepositType().equals(WalletConstant.DEPOSIT_WIREDTRANSFER)){
addActionMessage(getText("msg.success.tt"));
}else{
addActionMsg(getText("msg.success"));
}
transaction = new WalletTransaction();
} catch (Exception e) {
e.printStackTrace();
addActionErr(getText("Error in system.Please contact system's administrator."));
return ERROR;
}
execute();
return "paymount";
}
Thanks in advance
Use BigDecimal
BigDecimal bd = new BigDecimal(doubleValue);
bd = bd.setScale(2, RoundingMode.HALF_UP);
return bd.doubleValue();
Here RoundingMode.HALF_UP will round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
There are many ways of doing what you have asked for
1.
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
2.
double d = 1.234567;
System.out.printf("%1$.2f", d);
but I would never ever use double for money values anyways, I recommend you to take a look at BigDecimals
EDIT: look # Zeeshan ´s answer if you want to convert Double to Big Decimal.
but the best is to ONLY use Big Decimal for money values, then you will never have any rounding issues # converting.
Use DecimalFormat
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(rateConv));
Try like this:
double amount = 123;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(amount));
Related
I require a DecimalFormat or a better equivalent of representing a Double value (in Java) which could be:
25 or 25.5
I need for that to be represented as either a whole number (25) or to two decimal places if it has any (25.50). This is because i'm printing it out as money.
I have the following format already:
DecimalFormat decFormat = new DecimalFormat("##,###.##");
This works perfectly if the Double is a whole number; I get the output $25,000. Except if the value is 25,000.5; it prints $25,000.5 when I need it to be printed as $25,000.50. The problem is as stated in the docs:
# a digit, zero shows as absent
So essentially the last zero is dropped off since it is optional.
I cannot do:
DecimalFormat decFormat = new DecimalFormat("##,###.#0");
as that is not allowed.
How can I achieve this?
Note:
These questions are related but do not cover what I need specifically with the DecimalFormat. Most of the answers suggest using a BigDecimal or printf. Is this the best thing to do? I don't have to use DecimalFormat but prefer to since i've started on that path (lots of code everywhere already using it).
Best way to Format a Double value to 2 Decimal places
How do I round a double to two decimal places in Java?
Round a double to 2 decimal places
This is definitely a bit of a hack, but I don't know if the DecimalFormat syntax allows for anything better. This simply checks to see if the number is real, and formats based on the spec you asked for.
double number = 25000.5;
DecimalFormat df;
if(number%1==0)
df = new DecimalFormat("##,###");
else
df = new DecimalFormat("##,###.00");
System.out.println(df.format(number));
When you need to return Decimal Format value this works
import java.text.DecimalFormat;
/**
* #return The weight of this brick in kg.
*/
public double getWeight()
{
DecimalFormat df = new DecimalFormat("#.##");
double number = ( getVolume() * WEIGHT_PER_CM3 ) / 1000;
//System.out.println(df.format(number));
return Double.valueOf ( df.format( number ) );
}
This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I have a Double value Double val = 49.569632
How can I roundup the val to get 49.57
You can use the DecimalFormat.
double d = 4.569632;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Or you can use the below method as mentioned in this answer as Luiggi Mendoza suggested.
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
A simple way to round is when printing
double val = 49.569632; // this should be a primitive, not an object
System.out.printf("%.2f%n", val);
or you can round the value first
double rounded = Math.round(val * 1e2) / 1e2;
System.out.println(rounded);
IMHO Using BigDecimal is slower, more complicated to write and no less error prone than using double if you know what you are doing. I know many developer prefer to use a library than write code themselves. ;)
I'm trying to round a double to the nearest two decimal places however, it is just rounding to the nearest full number.
For example, 19634.0 instead of 19634.95.
This is the current code I use for the rounding
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;
I can't see where i am going wrong.
Many thanks for any help.
Well, Math.round(Math.PI*Radius()*Radius()*100) is long. 100 is int.
So Math.round(Math.PI*Radius()*Radius()*100) / 100 will become long (19634).
Change it to Math.round(Math.PI*Radius()*Radius()*100) / 100.0. 100.0 is double, and the result will also be double (19634.95).
You can use a DecimalFormat object:
DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);
System.out.println (df.format (19634.95));
Do you actually want want to round the value to 2 places, which will cause snowballing rounding errors in your code, or simply display the number with 2 decimal places? Check out String.format(). Complex but very powerful.
You might want to take a look at the DecimalFormat class.
double x = 4.654;
DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());
This gives "x=4.65". The difference between # and 0 in the pattern is that the zeros are always displayed and # will not if the last ones are 0.
The following example came from this forum, but seems to be what you are looking for.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Closed 3 years ago.
Having a lot of trouble rounding a value to display in a textView.
I basically wanna round it to two decimal places but at the moment I am getting a long trail of different numbers.
I am playing around with BigDecimal but no luck so far...
public void calc() {
BigDecimal bd = new BigDecimal(subTotal);
bd.setScale(2, BigDecimal.ROUND_DOWN);
total.setText(String.valueOf(bd));
}
Try the following code:
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
Following worked for me
BigDecimal bd = new BigDecimal(subTotal);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
total.setText(String.valueOf(bd));
// Input: 9.888888 -> Output: 9.89
// Input: 9f -> Output: 9.00
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 1 year ago.
I want to truncate a float and a double value in java.
Following are my requirements:
1. if i have 12.49688f, it should be printed as 12.49 without rounding off
2. if it is 12.456 in double, it should be printed as 12.45 without rounding off
3. In any case if the value is like 12.0, it should be printed as 12 only.
condition 3 is to be always kept in mind.It should be concurrent with truncating logic.
try this out-
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));
Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.
The expected result is:
12.49
12.45
12
double d = <some-value>;
System.out.println(String.format("%.2f", d - 0.005);
I have the same problem using Android, you can use instead:
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
but for this API Level 9 is required.
Another fast solution is:
double number = 12.43543542;
int aux = (int)(number*100);//1243
double result = aux/100d;//12.43
take a look with DecimalFormat() :
DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
Check java.math.BigDecimal.round(MathContext).
Try using DecimalFormat and set the RoundingMode to match what you need.