【问题标题】:Recurring Numbers: How to get a non-rounded recurring number when dividing a number by another number?循环数:将一个数字除以另一个数字时如何获得一个非四舍五入的循环数?
【发布时间】:2019-12-20 11:48:43
【问题描述】:

我正在尝试解决一个涉及循环数字的特定 JavaScript 练习,为此我需要处理循环数字到大量小数位。

目前我正在使用:

function divide(numerator, denominator){
    var num = (numerator/parseFloat(denominator);
}
// 7/11 = 0.6363636363636364
// 5/3 = 1.6666666666666667
// 3/8 = 0.375

如您所见,包含重复数字的运算结果将返回最后一位四舍五入的数字。简单地将每个数字的最后一位转换为数组和 pop() 是很诱人的,但是当我们遇到诸如 3/8 =0.375 之类的非重复数字时,这会导致问题。

如何将两个数字相除并得到 5/3 = 1.666666666666666 之类的结果? (基本上最后一位是向下取整,从不向上取整)

感谢您的帮助。

【问题讨论】:

标签: javascript numbers decimal


【解决方案1】:

对于简单的情况,我通常使用round-to npm 包:

import roundTo from 'round-to';

const num = 5/3; // 1.6666666666666667
// set your desired number of decimal places:
const numDecimalPlaces = (num + "").split(".")[1].length; 
// Based on your question, I think this is what you are trying to achieve:
const roundedDown = roundTo.down(num, numDecimalPlaces - 1); // 1.6666666666666667
// You can also do these:
const rounded = roundTo(num, numDecimalPlaces); // 1.6666666666666667
const roundedUp = roundTo.up(num, numDecimalPlaces); // 1.6666666666666667

如果你不想安装他们的包,你可以从 Github 复制他们的实现。他们的源代码很容易理解。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多