Reputation: 1
Someone who can help me making this round up to two decimals instead of showing all of the decimals in android?
Upvotes: 0
Views: 4820
Reputation: 208
try this:
//continuing from code
Udregning = aValue * EuroTilKroner;
String abc = String.format("%.2f", Udregning);
result.setText(abc);
Upvotes: 0
Reputation: 233
public static String roundAndFormatDouble(double value,int scale) {
try {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(scale, RoundingMode.HALF_UP);
String roundedValue = bd.toString();
return roundedValue;
} catch (Exception e) {
e.printStackTrace();
}
return ""+value;
}
Both the rounding and formatting part can be handled with this API.
Please note if you use bd,doubleValue(), you might not get exactly scaled number of decimal place in some cases.For eg: 50.0.
Upvotes: 0
Reputation: 26007
Use the code below. This will give you a string in return with just 2 decimal places.
// Continuing from the code you have on thee link ...
double Udregning = aValue * EuroTilKroner;
DecimalFormat df = new DecimalFormat("#.00");
String s = df.format(Udregning);
result.setText(s);
Hope this helps else please comment.
Update
As @Oren nicely suggested, you may set the rounding mode as follows:
df.setRoundingMode(RoundingMode.HALF_EVEN);
For more modes see the link.
Upvotes: 1
Reputation: 996
You can use String.format("%.2f", value)
, your double will be rounded automatically.
Upvotes: 0