Reputation: 3108
I have below code:
Double a = new Double((123456798/1000000)); //123456798 this value comes from client side as a `int`
DecimalFormat df = new DecimalFormat("###.###");
log.info("a :"+a+" df "+df.format(a.doubleValue()));
output:
a :123.0 df 123
//i want output like this, a :123.xxx fd 123.xxx
please help
UPDATE:
123456798 this value comes from client side as a int
so i cant do it as 123456798.0 (or something)
Upvotes: 1
Views: 811
Reputation: 7069
Any one value in the division should be float or double.
Double a = new Double((123456798.0/1000000));
or
Double a = new Double((123456798/1000000.0));
if you are getting these values in variables, then multiply it with 1.0
like
Double a = new Double((variable*1.0/1000000));
Upvotes: 2
Reputation: 310993
123456798
and 1000000
are int
literals, so dividing them will use integer arithmetic, and yield 123
.
Instead, you could use floating point literals in order to use floating point arithmetic:
Double a = new Double((123456798.0/1000000.0));
DecimalFormat df = new DecimalFormat("###.###");
log.info("a :"+a+" df "+df.format(a.doubleValue()));
Upvotes: 3
Reputation: 206776
Double a = new Double((123456798/1000000));
You are doing integer division here. Make one of the constants a double
, so that floating-point division is done. Also, why are you using Double
? It's better to use the primitive type double
.
double a = 123456798.0 / 1000000;
Or simply, since they are constants:
double a = 123.456789;
Upvotes: 1
Reputation: 186668
Put it like that
Double a = new Double((123456798.0/1000000.0)); // <- note ".0"
the reason of the misbehavior is the integer division:
123456798/1000000
is the integer value, while
123456798.0/1000000.0
is the floating point one (double)
Upvotes: 1
Reputation: 18123
You perform an integer division, thats why a
is incorrect:
Double a = new Double(123456798.0/1000000);
Upvotes: 0