[英]convert double values in decimal (fraction) values java
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) 123456798此值来自客户端,作为
int
所以我无法将其作为123456798.0(或其他方式)
123456798
and 1000000
are int
literals, so dividing them will use integer arithmetic, and yield 123
. 123456798
和1000000
是int
文字,因此将它们相除将使用整数算术,并产生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()));
Any one value in the division should be float or double. 除法中的任何一个值都应为float或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
如果要通过变量获取这些值,则将其
multiply it with 1.0
like 喜欢
Double a = new Double((variable*1.0/1000000));
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) 是浮点数一(双)
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. 将常量之一设为
double
,以便完成浮点除法。 Also, why are you using Double
? 另外,为什么要使用
Double
? It's better to use the primitive type double
. 最好使用原始类型
double
。
double a = 123456798.0 / 1000000;
Or simply, since they are constants: 或者简单地说,因为它们是常量:
double a = 123.456789;
您执行整数除法,这就是a
不正确的原因:
Double a = new Double(123456798.0/1000000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.