Round a double in Java

前端 未结 6 1084
余生分开走
余生分开走 2020-12-08 00:31

I have found this great solution for rounding:

static Double round(Double d, int precise) {
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = b         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 00:36

    Rounding a double resp Double in itself does not make much sense, as a double datatype cannot be rounded (easily, or at all?).

    What you are doing is:

    1. Take a Double d as input and a int precise number of digits behind the seperator.
    2. Create a BigDecimal from that d.
    3. Round the BigDecimal correctly.
    4. Return the double value of that BigDecimal, which has no rounding applied to it anymore.

    You can go two ways:

    1. You can return a BigDecimal that represents the rounded double, and later decide what you do with it.
    2. You can return a String representing the rounded BigDecimal.

    Either of those ways will make sense.

提交回复
热议问题