如何将浮点数舍入到最接近的整数然后在JAVA中转换为double?

时间:2014-04-24 11:34:44

标签: java rounding

我有一个浮动值

float myValue=5.1824203;
  • 如何将浮动舍入到最接近的整数然后转换为 双?
  • 实现这一目标的最佳方法是什么?

谢谢,

3 个答案:

答案 0 :(得分:0)

以这种方式尝试:

public static void main(String arguments[]) {
    float myValue=5.1824203f;
    int rounded = Math.round(myValue);
    System.out.println("as int: " + rounded);
    float floated = (float) rounded;
    System.out.println("as float: " + floated);
}

输出:

as int: 5
as float: 5.0

答案 1 :(得分:0)

float myValue=5.1824203f;
double rounded = Math.round(myValue);

请注意浮动myValue初始化的区别。

答案 2 :(得分:0)

double myRoundedDoubleValue = Math.round(myValue);