0

我正在使用这段代码:

$("#total_percentage").text(
    (parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10))
);

我的问题是 #total_percentage 有时会给出很长的结果。

例如:2.33333333333

有没有办法设置它,所以它四舍五入/只显示最多 2 位数字?

例如:2 或 10

4

3 回答 3

1

If you want to display two digits to the right of the decimal, Math.toFixed is the solution:

(2.33333333).toFixed(2) === "2.33"

Note that this results in a string, not a number. If you want to display 2 digits total, Math.toPrecision is what you want:

(2.33333333).toPrecision(2) === "2.3"

Again, this results in a string. To get back to a number (if desired), you can use parseFloat.

A final note that both these functions will also round your number. For example:

(1.23456).toPrecision(4) === "1.235"

If you want to truncate your number without rounding, you can write a function like this:

function truncate(num,precision) {
    var muldiv = Math.pow(10,precision-1);
    return Math.floor(num * muldiv) / muldiv;
}

truncate(1.23456,4) === 1.234

Here is a jsFiddle demonstrating each method:

---jsFiddle DEMO---

于 2012-08-15T19:13:15.707 回答
1

您可以使用toFixed()

$("#total_percentage").text(
    (parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)).toFixed(2)
);

参考:

于 2012-08-15T18:46:29.757 回答
1

要四舍五入,请使用 Javascript 数学库。

$("#total_percentage").text(
    (Math.ceil(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)))
);
于 2012-08-15T18:46:45.063 回答