Java 在不丢失确切值的情况下将 Double 转换为 long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19868181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a Double to long without loosing the exact value
提问by Abs
I have a Doubleobject which looses the exact value when converted to longvalue.
我有一个Double对象在转换为long值时会丢失确切的值。
Double d = 1.14*100
System.out.println(d.longValue());
The above statement would print : 113.
上面的语句将打印 : 113。
I want 114to be printed.
我想114被打印。
Thanks
谢谢
采纳答案by Donvino
If you need the exact 114 value you ned to use Math.round:
如果您需要使用的确切 114 值Math.round:
double d = 1.14*100;
System.out.println(Math.round(d));
回答by Bohemian
Firstly, a doubleis notexact. Next, when castinga double/floatto a long/int, the decimal part is dropped (not rounded).
首先,double是不准确的。接下来,当铸造一个double/float到long/ int,小数部分被丢弃(不四舍五入)。
To get the nearestvalue, you'll need to roundit:
要获得最接近的值,您需要对其进行四舍五入:
System.out.println(Math.round(d));
回答by user2871923
If you are looking for an integer / long value representation with the value you are expecting, you can use this:
如果您正在寻找具有您期望的值的整数/长值表示,您可以使用:
Math.round(1.14 * 100)
回答by Jans
Try this
尝试这个
Long.parseLong( String.format( "%.0f",doublevalue ) ) ;

