开发者

Rounding off values in Java

I have a double variable which outputs some values. Examples:

    开发者_高级运维
  • If value = 62.42, I want to round off the value to 62.

  • If value = 62.99, I want to round off the value to 62.

No matter what comes in decimal places, it should only show the whole value.


Math.floor(double a)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.


The following yields 62 in both cases.

public class Round {
    public static void main(String[] args) throws Exception {
        System.out.println((int)Math.floor(62.99));
        System.out.println((int)Math.floor(62.42));
    }
}

Using Math.floor

Or you could use Math.round(Math.floor(double a))


Cast it as an int. This truncates the double value to integer part, discarding any decimal part of the number.

eg.

double d = 1.7;
int i = (int) d; // i = 1


have you tried assigning this decimal value to an integer? like this:

int val = value; //where value = 62.42;


double doubleRounded = Math.round(doubleWithDecimals);
double doubleFloored = Math.floor(doubleWithDecimals);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜