How to round integer in java

后端 未结 12 759
野趣味
野趣味 2020-12-09 09:19

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for

12条回答
  •  有刺的猬
    2020-12-09 09:45

    Use Precision (Apache Commons Math 3.1.1)

    Precision.round(double, scale); // return double
    Precision.round(float, scale); // return float
    

    Use MathUtils (Apache Commons Math) - Older versions

    MathUtils.round(double, scale); // return double
    MathUtils.round(float, scale); // return float
    

    scale - The number of digits to the right of the decimal point. (+/-)


    Discarded because method round(float, scale) be used.

    Math.round(MathUtils.round(1732, -1)); // nearest ten, 1730
    Math.round(MathUtils.round(1732, -2)); // nearest hundred, 1700
    Math.round(MathUtils.round(1732, -3)); // nearest thousand, 2000


    Better solution

    int i = 1732;
    MathUtils.round((double) i, -1); // nearest ten, 1730.0
    MathUtils.round((double) i, -2); // nearest hundred, 1700.0
    MathUtils.round((double) i, -3); // nearest thousand, 2000.0
    

提交回复
热议问题