将十进制数转换为javascript中的分数或最接近的分数 [英] convert decimal number to fraction in javascript or closest fraction

查看:128
本文介绍了将十进制数转换为javascript中的分数或最接近的分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我希望能够将任何十进制数转换为分数。在两种形式中,例如没有剩余的形式如下: 3/5 或余数: 3 1/4



我在做什么就是这个......



假设我的号码是.3435。




  • 计算小数点后的位数。

  • 乘以数字前的数量乘以10。

  • 然后以某种方式找到最大的共同因素。



现在我不知道如何找到GCF。而且我也不知道如何实现逻辑来找到代表数字的分数或者如果精确分数不存在则以其余形式表示。



我到目前为止的代码:(测试)

  x = 34/35; 
a = x - x.toFixed();
tens =(10).pow(a.toString()。length - 2);

numerator = tens * x;
分母=数十;


解决方案

您的前两个步骤是合理的。



但你应该做的是分子和分母计算最大公约数(GCD)然后将分子和分母除以该除数以得到你想要的分数。



GCD相当容易计算。这是 Euclid的算法

  var gcd = function(a,b){
if(!b)return a;

返回gcd(b,a%b);
};

修改



<我已经添加了一个完全有效的 JSFiddle


So i want to be able to convert any decimal number into fraction. In both forms such as one without remainder like this: 3/5 or with remainder: 3 1/4.

what i was doing is this..

lets say i have number .3435.

  • Calculate amount of digits after decimals.
  • multiply by 10 with power of the amount before number.
  • then somehow find greatest common factor.

Now i don't know how to find GCF. And nor i know how to implement logic to find fraction that represents a number closely or in remainder form if exact fraction doesn't exists.

code i have so far: (testing)

x = 34/35;
a = x - x.toFixed();
tens = (10).pow(a.toString().length - 2);

numerator = tens * x;
denominator = tens;

解决方案

Your first 2 steps are reasonable.

But what you should do is for the numerator and denominator calculate the Greatest Common Divisor (GCD) and then divide the numerator and denominator with that divisor to get the fraction you want.

GCD is rather easy to calculate. Here is Euclid's algorithm:

var gcd = function(a, b) {
  if (!b) return a;

  return gcd(b, a % b);
};

Edit

I've added a fully working JSFiddle.

这篇关于将十进制数转换为javascript中的分数或最接近的分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆