简体   繁体   English

将2十进制转换为整数

[英]Convert 2 decimal to integer

I want to convert number 2.55 to 255 in java. 我想在java中将数字2.55转换为255

I have tried the following code but I am getting 254 instead of 255 : 我尝试了以下代码,但我得到的是254而不是255

final Double tmp = 2.55;
final Double d = tmp * 100;
final Integer i = d.intValue();

What is the correct way to achieve this? 实现这一目标的正确方法是什么?

you have to round that value, and you can use primitives for that.. ie use the primitive double instead of the wrapper class Double 你必须舍入该值,你可以使用原语...即使用原始double而不是包装类Double

    final double tmp = 2.55;
    final double d = tmp * 100;
    long i = Math.round(d);

    System.out.println("round: "+ i);

It is simple by using BigDecimal 使用BigDecimal很简单

    BigDecimal bg1 = new BigDecimal("123.23");
    BigDecimal bg2 = new BigDecimal("12323");

    bg1= bg1.movePointLeft(-2); // 3 points right

    bg2= bg2.movePointLeft(3);  // 3 points left


    System.out.println(bg1);     //12323

    System.out.println(bg2);     //12.323

the value of d is 254.999999999997. d的值是254.999999999997。 this is a problem with floating point calculations. 这是浮点计算的问题。 you could use 你可以用

i = Math.round(d);

to get 255. 得到255。

--- delete the bottom.. was wrong ---删除底部..错了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM