[英]How to convert decimal to whole number in java
Hi i have an output as "1.234567E6" and similar.嗨,我有一个 output 作为“1.234567E6”和类似的。 Now i want my output to be converted to 1234567. Could you please suggest how to acheive this?现在我想将我的 output 转换为 1234567。您能否建议如何实现这一点? Splitting is one way but then E6 part handling i am not sure.拆分是一种方法,但我不确定 E6 部分的处理。
Also the output will be varying in nature, sometimes it would be 6 decimal places, sometimes 10 output 的性质也会有所不同,有时是小数点后 6 位,有时是 10
You can use Double.valueOf
then get the long value您可以使用Double.valueOf
然后获取长值
long val = Double.valueOf("1.234567E6").longValue();
Or use BigDecimal with longValueExact()
to avoid rounding error或者使用 BigDecimal 和longValueExact()
来避免舍入错误
long val = new BigDecimal("1.234567E10").longValueExact();
Note: longValueExact()
throws Arithmetic Exception if there is any fractional part of this BigDecimal.注意:如果 BigDecimal 有任何小数部分, longValueExact()
将引发算术异常。
Use DecimalFormat
, it's consistent and clear approach:使用DecimalFormat
,这是一致且清晰的方法:
DecimalFormat decimalFormat = new DecimalFormat("0");
System.out.println( decimalFormat.format( 1.234567E6 ) );
In String case:在字符串情况下:
System.out.println( decimalFormat.format( Double.parseDouble("1.234567E6") ) );
Output in both cases Output 在这两种情况下
1234567 1234567
See code in action: http://tpcg.io/9DsB3GRH请参阅实际代码: http://tpcg.io/9DsB3GRH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.