【问题标题】:toPrecision rounding directionto精确舍入方向
【发布时间】:2018-12-15 23:45:50
【问题描述】:

Javascript 的 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

【问题讨论】:

  • Math.floor(123.46) -> 123
  • @dGRAMOP,我认为 DBS 意味着您可以使用它(但显然需要进行一些额外的操作)。
  • 啊,我看错了。我的坏

标签: javascript precision


【解决方案1】:

这不是一个班轮,但我认为这可以满足您的要求吗?你可以稍微整理一下。

编辑更新(以相当基本的方式)以使用有效数字而不是小数

EDIT 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
*/

JS Fiddle link

【讨论】:

  • 放弃了我的答案,与我所做的非常相似,只是我使用了 math.pow
  • 在我意识到 toPrecision 不仅仅是小数,它是有效数字之前,我正在写类似的东西,我相信这使得这种方法与内置的 toPrecision 不一致,虽然我可能弄错了。
  • 是的,我正要回复:toPrecission 是有效位数的总数,而不是小数位数
  • 好点,我已经尝试编辑以反映这一点 - 更好吗?
  • 几乎!。试试 12340000,这里(节点 8)给出 12299999.999999998。问题在于可能会再次引入不精确性的划分。但是除以 10 的幂,只需将小数点放在字符串中...
【解决方案2】:

我知道这是一篇旧帖子,但我一直在做类似的事情。在已知数字的小数位数的情况下,您可以进行简单的减法并按原样使用精度函数。

在我自己的情况下,我试图四舍五入到最近的世纪,所以在使用 toPrecision 函数之前,我会从值中减去 50 年,这使得该函数能够产生您正在寻找的相同最终结果。在原始帖子的示例中,如果精度始终为 4 位并且数字采用 ddd.dd 格式,那么您可以在调用精度函数之前简单地从数字中删除 0.05。同样,如果你想四舍五入,你可以添加 0.05

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2017-06-10
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多