Manel Chaabene - 10 months ago 37

Java Question

I have a number as

`number a= 2.944127983333377`

`2.94`

I searched and I found

`new DecimalFormat("##.##").format(a)`

But the problem that it's type is string and not number.

Answer

You could try this:

```
double value= 2.944127983333377;
// Multiply it by 100, convert the result into an integer to trim
// remaining decimals then divide it by 100d to get the result as double
double result = (int)(value * 100) / 100d;
System.out.println(result);
```

**Output:**

```
2.94
```

If you want a `Number`

, simply replace the type `double`

of `result`

with `Number`

, thanks to autoboxing it will convert automatically the `double`

into a `Double`

which is a sub class of `Number`

:

```
Number result = (int)(value * 100) / 100d;
```

Source (Stackoverflow)