cuốn sách gpt4 ai đã làm

JavaScript:四舍五入 100

In lại Tác giả: Walker 123 更新时间:2023-11-28 11:05:07 26 4
mua khóa gpt4 Nike

我正在尝试将数字四舍五入到 100。

Ví dụ:

1340 should become 1400
1301 should become 1400

298 should become 300
200 should stay 200

Tôi biếtMath.round但它不会四舍五入到 100。

我怎样才能做到这一点?

câu trả lời hay nhất

原始答案

sử dụngMath.ceil函数,如:

var result = 100 * Math.ceil(value / 100);

通用版本

这个函数可以概括如下:

Number.prototype.roundToNearest = function (multiple, roundingFunction) {
// Use normal rounding by default
roundingFunction = roundingFunction || Math.round;

return roundingFunction(this / multiple) * multiple;
}

然后您可以按如下方式使用此功能:

var value1 = 8.5;
var value2 = 0.1;

console.log(value1.roundToNearest(5)); // Returns 10
console.log(value1.roundToNearest(5, Math.floor)); // Returns 5
console.log(value2.roundToNearest(2, Math.ceil)); // Returns 2

或者使用自定义舍入函数(例如 banker's rounding ):

var value1 = 2.5;
var value2 = 7.5;

var bankersRounding = function (value) {
var intVal = Math.floor(value);
var floatVal = value % 1;

if (floatVal !== 0.5) {
return Math.round(value);
} khác {
if (intVal % 2 == 0) {
return intVal;
} khác {
return intVal + 1;
}
}
}

console.log(value1.roundToNearest(5, bankersRounding)); // Returns 0
console.log(value2.roundToNearest(5, bankersRounding)); // Returns 10

运行代码的示例是 available here .

关于JavaScript:四舍五入 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17405899/

26 4 0
Đề xuất bài viết: javascript - 这是什么字符编码?
Đề xuất bài viết: javascript - 如何禁用F5键盘按键
Đề xuất bài viết: css - 组合 CSS 文件功能
Đề xuất bài viết: javascript - 在javascript中同时循环两个数组
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress