Manel Chaabene Manel Chaabene - 10 months ago 37
Java Question

How to get 2 digit after the decimal point with number type

I have a number as

number a= 2.944127983333377
Now I want to formatted it as
I searched and I found
new DecimalFormat("##.##").format(a)

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


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;



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;