gpt4 book ai didi

javascript - 重复出现的数字 : How to get a non-rounded recurring number when dividing a number by another number?

转载 作者:行者123 更新时间:2023-12-02 02:29:33 30 4
gpt4 key购买 nike

我正在尝试解决涉及重复数字的特定 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 之类的结果? (基本上最后一位数字向下舍入,并且从不向上舍入)

感谢您的帮助。

最佳答案

对于简单的情况,我通常使用 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 复制他们的实现。他们的源代码非常容易理解。

关于javascript - 重复出现的数字 : How to get a non-rounded recurring number when dividing a number by another number?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59424811/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com