我正在尝试解决一个涉及递归数字的特定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的结果?(基本上最后一个数字是向下舍入的,而不是向上舍入的)
谢谢你的帮助。
发布于 2019-12-21 01:24:06
对于简单的情况,我通常使用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复制他们的实现。他们的源代码很容易理解。
https://stackoverflow.com/questions/59424811
复制相似问题