Weekly - issue 35

JavaScript、Python、Java 中精确的四舍五入

下面的例子均是精确到小数点后两位。结果均是 2.35

JavaScript:

const number = 2.345;
const roundedNumber = (Math.round(number * 100) / 100).toFixed(2)
console.log(roundedNumber)

Python:

from decimal import Decimal, ROUND_HALF_UP

number = 2.345
rounded_number = Decimal(number).quantize(Decimal('0.00'), rounding = ROUND_HALF_UP)
print(rounded_number)

Java:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        float number = 2.345f;
        float roundedNumber = new BigDecimal(number).setScale(2, RoundingMode.HALF_UP).floatValue();
        System.out.println(roundedNumber);
    }
}

Intel One Mono

Intel’s open source monospace font.