Java的toPrecision约等于四舍五入
(123.46).toPrecision(4) // 123.5
(123.44).toPrecision(4) // 123.4
但是,选择舍入方向(上/下或下/下)的简单方法是什么?所以
(123.46).toPrecisionFloor(4) // would give 123.4
(123.44).toPrecisionCeil(4) // 123.5
答案 0 :(得分:1)
这不是一个班轮,但我认为这符合您的要求?您可能可以整理一下。
编辑(以一种非常基本的方式)进行了更新,可以处理有效数字而不是小数
编辑2 稍微弄清代码并添加了进一步的测试
/**
* rounds a number up or down to specified accuracy
* @param number {numeric} number to perform operations on
* @param precision {numeric} number of significant figures to return
* @param direction {string} wether to round up or down
*/
function toPrecision(number, precision, direction) {
precision -= Math.floor(number).toString().length;
var order = Math.pow(10, precision);
number *= order;
var option = (direction === 'down' ? 'floor' : 'ceil');
return (Math[option].call(null, number) / order);
}
// values to test
var test_1 = 123.567891;
var test_2 = 15000;
var test_3 = 12340000;
// define tests
var tests = {
"a": [test_1, 3, "down"],
"b": [test_1, 4, "up"],
"c": [test_2, 3, "down"],
"d": [test_2, 4, "up"],
"e": [test_2, 1, "down"],
"f": [test_2, 1, "up"],
"g": [test_3, 4, "down"],
"h": [test_3, 4, "up"]
}
// loop over tests and execute
for (var key in tests) {
console.log("key:", key, "result: ", toPrecision.apply(null, tests[key]));
}
/*
Test results:
key: a result: 123
key: b result: 123.6
key: c result: 15000
key: d result: 15000
key: e result: 10000
key: f result: 20000
key: g result: 12340000
key: h result: 12340000
*/