Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round decimal numbers in Android [duplicate]

Tags:

java

android

Possible Duplicate:
Double value to round up in Java

I am getting float number as input and I want it to round to 2 digits after decimal point. i.e. for example if I get 18.965518 as input, I want it to be 18.97. How to do it?

like image 341
Soniya Avatar asked Sep 19 '11 14:09

Soniya


People also ask

How do you round a double to two decimal places?

We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

How do you round a number on Android?

float x = 0.015; NumberFormat nf = DecimalFormat. getPercentInstance(); nf. setMaximumFractionDigits(0); output = nf. format(x);

How do you round up decimal numbers?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.


2 Answers

DecimalFormat uses String (thus allocates additional memory), a big overhead compared to

(float)Math.round(value * 100) / 100
like image 54
vmatyi Avatar answered Oct 23 '22 22:10

vmatyi


You can use the DecimalFormatobject, similar to regular Java.

Try

double roundTwoDecimals(double d)
{
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

(code example lifted from http://www.java-forums.org/advanced-java/4130-rounding-double-two-decimal-places.html)

like image 31
Richard Ev Avatar answered Oct 23 '22 20:10

Richard Ev