说我们有2/4分数,它可以减少到1/2.有没有可以减少的javascript函数?
我想找到使用JavaScript的最大公约数.
以前做过那些并愿意分享的人?
例如,如果我的函数被调用getlowestfraction(),这就是我期望它做的:
getlowestfraction(0.5) // returns 1, 2 or something along the lines of that
Run Code Online (Sandbox Code Playgroud)
另一个例子:
getlowestfraction(0.125) // returns 1, 8 or something along the lines of that
Run Code Online (Sandbox Code Playgroud) 我想用一个数字将小数转换为最接近的分数!\n例如,“8.75”应为“8 3/4”,“1.875”应为“1 7/8”,但“8,565217..” ." 不应该显示“8 13/23”,而是显示错误。\nExcel 中有一个类似的功能,解释如下
\n\n我还想避免使用像fraction.js 这样的第三个库,而更喜欢使用原生JS/TS 或Lodash!有人有主意吗?=)
\n\n感谢您的帮助!
\n\n编辑: \n我尝试了一部分代码,但没有按预期工作 cs 8.75 发送给我 35/4 而没有 8 3/4...
\n\n private checkNumberToCompute(numberToCompute: any) {\n let numberToReturn = numberToCompute;\n if (\n (!isNaN(Number(numberToCompute)) && numberToCompute.includes(\'.\')) ||\n (numberToCompute.includes(\',\') && !numberToCompute.includes(\'/\'))\n ) {\n console.log(\'Nombre \xc3\xa0 d\xc3\xa9cimal sans fraction\');\n numberToReturn = this.computeFractions(numberToCompute);\n }\n return numberToReturn;\n }\n private computeFractions(numberToCompute: any): string {\n console.log(\'numberToCompute\', numberToCompute);\n\n const lenghtOfDecimals = numberToCompute.substring(numberToCompute.indexOf(\'.\') + 1).length;\n let denominator = Math.pow(10, lenghtOfDecimals),\n numerator = numberToCompute * denominator;\n const …Run Code Online (Sandbox Code Playgroud)