0

I'm beginner in android developing. How can I make a double datatype i.e 56.32534 into 56.33? But I want to take it in a double variable. I know a way but it takes in String.

Double value = 56.32534;
DecimalFormat df = new DecimalFormat("0.##");
String newvalue = df.format(value);

Here, newvalueis a string. But I want to take it in a double datatype.

I need to use it's numeric value not just in display purpose only.

Utpal Barman
  • 51
  • 2
  • 9
  • The multiply/divide by 100 technique mentioned in several of these answers doesn't work most of the time. It can't. Doubles don't have decimal places. See my answer in the duplicated question for proof. – user207421 May 29 '15 at 00:49

2 Answers2

1

You can use Math.round():

double value = 56.32534;
double rounded = Math.round(100 * value) / 100.0;

The multiplication and then division by 100 is necessary because Math.round() rounds to the nearest long value.

If you want to generalize this to a variable number of digits, you can use something like this:

public double round(double value, int digits) {
    double scale = Math.pow(10, digits);
    return Math.round(value * scale) / scale;
}

This will even work if digits is not positive; it will round to the nearest integer if digits is 0, to the nearest 10 if digits is -1, to the nearest 100 if digits is -2, etc.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Thanks for the answer. Would you please explain if I want to take 3 digits after decimal point what I should do? – Utpal Barman May 28 '15 at 23:25
  • 1
    @UtpalBarman - It's very similar: `Math.round(1000 * value) / 1000.0;`. I'll update my answer to provide a general formula for any number of digits. Note that in all cases the divisor is a `double` literal; if you used an `int` literal, then you would need to cast the numerator to a `double` to avoid integer division. – Ted Hopp May 28 '15 at 23:31
-1

We need a little bit more precision on what you want to do. Do you want to display it that way or just use its numerical value that way ?

If it's the display your solution is ok. You could always get back the float number from the string afterwards.

On the other hand if you want to use it as a numerical value what you could do is

double rounded = (double) Math.round(myfloat * 100) /100; 

I think it works. Can't test it as I'm on my mobile though

LBes
  • 3,366
  • 1
  • 32
  • 66
  • I think you meant to use `tmp` in the second line. Otherwise `rounded` is just `myFloat` divided by 100. Also, casting to an `int` will truncate, not round. – Ted Hopp May 28 '15 at 23:18
  • You're right ! Edit on the way! Thanks for noticing :-) – LBes May 28 '15 at 23:20