Rounding double value for currency [duplicate] - java

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

Related

Big Decimal trim to two decimal places [duplicate]

This question already has an answer here:
Rounding BigDecimal to *always* have two decimal places
(1 answer)
Closed 2 years ago.
Below code gives me about 14 decimal places. How can i trim it to the 2 decimal place?
public class BigDecimalGenerator
{ public static void main(String[] args)
{ BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min.add(range.multiply(new BigDecimal(Math.random())));
System.out.println(result); }
}
Use this method on BigDecimal
setScale(int newScale, int roundingMode)
using the desired scale (2) and roundingmode.
Set the rounding mode and scale.
BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min
.add(range.multiply(new BigDecimal(Math.random())));
result = result.setScale(2,RoundingMode.HALF_UP);
System.out.println(result);
Prints something like.
-31.28

BigDecimal and rounding [duplicate]

This question already has answers here:
Rounding Bigdecimal values with 2 Decimal Places
(5 answers)
Closed 2 years ago.
I have been looking for answers here re: rounding and BigDecimal, but I am having trouble. Can someone help?
The actual result of the below division is 11.469...
BigDecimal a = new BigDecimal(0.32);
BigDecimal b = new BigDecimal(2.79);
BigDecimal diffPercent = (a.divide(b, 2, RoundingMode.HALF_EVEN)).multiply(HUNDRED); // 11.00
BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).multiply(HUNDRED); // 11.4700
How can I get 11.47 (two decimal places)?
Instead of multiplying by BigDecimal(100), move the decimal point to the right:
BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).movePointRight(2)
Output: 11.47
This works because moving the decimal point only adjusts the scale of the BigDecimal.
BigDecimal bg = new BigDecimal("11.468");
MathContext mc = new MathContext(3); // 3 precision
// bg1 is rounded using mc
final BigDecimal round = bg.round(mc, RoundingMode.CEILING);
System.out.println(round);
Posting as this is another example of how to round

Convert into 2 decimal points [duplicate]

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

Showing and not showing dot and decimals in float values? [duplicate]

This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 9 years ago.
How can I make a float value to only show the dot and the decimals if they exist. For example show 17 instead of 17.0 but if I have a 17.2 show the dot and the decimals.
Thanks!
You might also require to limit the length of fraction part, because there might a result like 12.00001 after a sequence of floating point operations. Code snippet I use to nicely format a double to a string:
private static final DecimalFormat[] formats= new DecimalFormat[]{
null,
new DecimalFormat("#.#"),
new DecimalFormat("#.##"),
new DecimalFormat("#.###"),
new DecimalFormat("#.####")
};
public static String toConciseString(double d, int fractionLength){
long asLong = (long) d;
if(Math.abs(d - asLong) < 0.00001d){
return Long.toString(asLong);
}
return formats[fractionLength].format(d);
}
Test cases showing the output examples:
assertThat(toConciseString(23.323, 2)).isEqualTo("23.32");
assertThat(toConciseString(23.329, 2)).isEqualTo("23.33");
assertThat(toConciseString(23.329, 3)).isEqualTo("23.329");
assertThat(toConciseString(23.3, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.30001, 2)).isEqualTo("23.3");
assertThat(toConciseString(23.00001, 2)).isEqualTo("23");
Try this:
DecimalFormat decimalFormat = new DecimalFormat("#0.##");
float float1 = 1.00f;
float float2 = 1.02f;
System.out.println(decimalFormat.format(float1));
System.out.println(decimalFormat.format(float2));
It will print out:
1
1.02

How to roundup a Double value up to two precision [duplicate]

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

Categories