在JavaScript中,有没有办法将十进制数字(例如0.0002
)转换为表示为字符串的分数(例如“2/10000"
”)?
如果为此目的编写了一个名为decimalToFraction
的函数,那么decimalToFraction(0.0002)
将返回字符串"2/10000"
。
答案 0 :(得分:21)
您可以使用Erik Garrison的fraction.js库来执行此操作以及更多小数操作。
var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);
要做.003你可以做到
var f = new Fraction(.003);
console.log(f.numerator + '/' + f.denominator);
答案 1 :(得分:8)
第一个小googling with the term "decimal to fraction js"产生了这个:
http://wildreason.com/wildreason-blog/2010/javascript-convert-a-decimal-into-a-simplified-fraction/
似乎有效:
function HCF(u, v) {
var U = u, V = v
while (true) {
if (!(U%=V)) return V
if (!(V%=U)) return U
}
}
//convert a decimal into a fraction
function fraction(decimal){
if(!decimal){
decimal=this;
}
whole = String(decimal).split('.')[0];
decimal = parseFloat("."+String(decimal).split('.')[1]);
num = "1";
for(z=0; z<String(decimal).length-2; z++){
num += "0";
}
decimal = decimal*num;
num = parseInt(num);
for(z=2; z<decimal+1; z++){
if(decimal%z==0 && num%z==0){
decimal = decimal/z;
num = num/z;
z=2;
}
}
//if format of fraction is xx/xxx
if (decimal.toString().length == 2 &&
num.toString().length == 3) {
//reduce by removing trailing 0's
decimal = Math.round(Math.round(decimal)/10);
num = Math.round(Math.round(num)/10);
}
//if format of fraction is xx/xx
else if (decimal.toString().length == 2 &&
num.toString().length == 2) {
decimal = Math.round(decimal/10);
num = Math.round(num/10);
}
//get highest common factor to simplify
var t = HCF(decimal, num);
//return the fraction after simplifying it
return ((whole==0)?"" : whole+" ")+decimal/t+"/"+num/t;
}
// Test it
alert(fraction(0.0002)); // "1/5000"
答案 2 :(得分:7)
我使用这个网站http://mathforum.org/library/drmath/view/51886.html来构建一个函数,但正如文章中提到的那样,你会得到一个不合理的大数字,用于激进派或者pi。
希望它有所帮助。
function Fraction(){}
Fraction.prototype.convert = function(x, improper)
{
improper = improper || false;
var abs = Math.abs(x);
this.sign = x/abs;
x = abs;
var stack = 0;
this.whole = !improper ? Math.floor(x) : 0;
var fractional = !improper ? x-this.whole : abs;
/*recursive function that transforms the fraction*/
function recurs(x){
stack++;
var intgr = Math.floor(x); //get the integer part of the number
var dec = (x - intgr); //get the decimal part of the number
if(dec < 0.0019 || stack > 20) return [intgr,1]; //return the last integer you divided by
var num = recurs(1/dec); //call the function again with the inverted decimal part
return[intgr*num[0]+num[1],num[0]]
}
var t = recurs(fractional);
this.numerator = t[0];
this.denominator = t[1];
}
Fraction.prototype.toString = function()
{
var l = this.sign.toString().length;
var sign = l === 2 ? '-' : '';
var whole = this.whole !== 0 ? this.sign*this.whole+' ': sign;
return whole+this.numerator+'/'+this.denominator;
}
//var frac = new Fraction()
//frac.convert(2.56, false)
//console.log(frac.toString())
//use frac.convert(2.56,true) to get it as an improper fraction
如果您只想要一个只返回分子和分母的自包含函数,那么请使用下面的函数。
var toFraction = function (dec) {
var is_neg = dec < 0;
dec = Math.abs(dec);
var done = false;
//you can adjust the epsilon to a larger number if you don't need very high precision
var n1 = 0, d1 = 1, n2 = 1, d2 = 0, n = 0, q = dec, epsilon = 1e-13;
while (!done) {
n++;
if (n > 10000) {
done = true;
}
var a = parseInt(q);
var num = n1 + a * n2;
var den = d1 + a * d2;
var e = (q - a);
if (e < epsilon) {
done = true;
}
q = 1 / e;
n1 = n2;
d1 = d2;
n2 = num;
d2 = den;
if (Math.abs(num / den - dec) < epsilon || n > 30) {
done = true;
}
}
return [is_neg ? -num : num, den];
};
//Usage:
//var frac = toFraction(0.5);
//console.log(frac)
//Output: [ 1, 2 ]
答案 3 :(得分:6)
很老的问题,但也许有人会觉得这很有用。它是迭代的,不是递归的,也不需要分解
function getClosestFraction(value, tol) {
var original_value = value;
var iteration = 0;
var denominator=1, last_d = 0, numerator;
while (iteration < 20) {
value = 1 / (value - Math.floor(value))
var _d = denominator;
denominator = Math.floor(denominator * value + last_d);
last_d = _d;
numerator = Math.ceil(original_value * denominator)
if (Math.abs(numerator/denominator - original_value) < tol)
break;
iteration++;
}
return {numerator: numerator, denominator: denominator};
};
答案 4 :(得分:3)
使用数字的字符串表示
有一个非常简单的解决方案 string = function(f){ // returns string representation of an object or number
return f+"";
}
fPart = function(f){ // returns the fraction part (the part after the '.') of a number
str = string(f);
return str.indexOf(".")<0?"0":str.substring(str.indexOf(".") + 1);
}
wPart = function(f){ // returns the integer part (the part before the '.') of a number
str = string(f);
return str.indexOf(".")<0?str:str.substring(0, str.indexOf(".")); // possibility 1
//return string(f - parseInt(fPart(f))); // just substract the fPart
}
power = function(base, exp){
var tmp = base;
while(exp>1){
base*=tmp;
--exp;
}
return base;
}
getFraction = function(f){ // the function
var denominator = power(10, fPart(f).length), numerator = parseInt(fPart(f)) + parseInt(wPart(f))*denominator;
return "[ " + numerator + ", " + denominator + "]";
}
console.log(getFraction(987.23));
只检查分数中有多少个数,然后扩展f / 1的分数,直到f为整数。这可能导致巨大的分数,因此您可以通过将分子和分母除以两者的最大公约数来减少它,例如
// greatest common divisor brute force
gcd = function(x,y){
for(var i = Math.min(x, y);i>0;i--) if(!(x%i||y%i)) return i;
return 1;
}
答案 5 :(得分:2)
好消息是它有可能,但您必须将其转换为代码。
让我们毫无理由地选择2.56。
使用数字.56
的小数部分.56中有2位数字,将.56写为56/100。
所以我们有2 + 56/100并且需要通过将分子和分母除以greatest common divisor来将这个分数减少到最低项,在这种情况下为4。
因此,该分数降至最低值为2 + 14/25。
要添加整数2,我们乘以除数并加到14
(2 * 25 + 14)/ 25 = 64/25
答案 6 :(得分:0)
尝试过这样的事情吗?
<script type="texrt/javascript>
var cnum = 3.5,deno = 10000,neww;
neww = cnum * deno;
while(!(neww % 2 > 0) && !(deno % 2 > 0)){
neww = neww / 2;
deno = deno / 2;
}
while(!(neww % 3 > 0) && !(deno % 3 > 0)){
neww = neww / 3;
deno = deno / 3;
}
while(!(neww % 5 > 0) && !(deno % 5 > 0)){
neww = neww / 5;
deno = deno / 5;
}
while(!(neww % 7 > 0) && !(deno % 7 > 0)){
neww = neww / 7;
deno = deno / 7;
}
while(!(neww % 11 > 0) && !(deno % 11 > 0)){
neww = neww / 11;
deno = deno / 11;
}
while(!(neww % 13 > 0) && !(deno % 13 > 0)){
neww = neww / 13;
deno = deno / 13;
}
while(!(neww % 17 > 0) && !(deno % 17 > 0)){
neww = neww / 17;
deno = deno / 17;
}
while(!(neww % 19 > 0) && !(deno % 19 > 0)){
neww = neww / 19;
deno = deno / 19;
}
console.log(neww+"/"+deno);
</script>
答案 7 :(得分:0)
我做了popnoodles建议的内容,这里是
function FractionFormatter(value) {
if (value == undefined || value == null || isNaN(value))
return "";
function _FractionFormatterHighestCommonFactor(u, v) {
var U = u, V = v
while (true) {
if (!(U %= V)) return V
if (!(V %= U)) return U
}
}
var parts = value.toString().split('.');
if (parts.length == 1)
return parts;
else if (parts.length == 2) {
var wholeNum = parts[0];
var decimal = parts[1];
var denom = Math.pow(10, decimal.length);
var factor = _FractionFormatterHighestCommonFactor(decimal, denom)
return (wholeNum == '0' ? '' : (wholeNum + " ")) + (decimal / factor) + '/' + (denom / factor);
} else {
return "";
}
}
答案 8 :(得分:0)
我只想要一个替代方案,我发现将十进制数转换为分数和减少分数,它是一个JS库。
图书馆调用fraction.js,这对我来说真的很有帮助,也节省了我很多时间和工作。 希望对其他人有用!
答案 9 :(得分:0)
这可能有点旧,但发布的代码在0值上失败我修复了该错误并将在下面发布更新的代码
getData
答案 10 :(得分:0)
我知道这是一个老问题,但我已经创建了一个大大简化的功能。
setInterval(() => {this.getfeed()},1000);
使用Math.fraction=function(x){
return x?+x?x.toString().includes(".")?x.toString().replace(".","")/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length))+"/"+("1"+"0".repeat(x.toString().split(".")[1].length))/(function(a,b){return b?arguments.callee(b,a%b):a;})(x.toString().replace(".",""),"1"+"0".repeat(x.toString().split(".")[1].length)):x+"/1":NaN:void 0;
}
它会:
Math.fraction(2.56)
(对包含分子和分母的数组使用string
)请注意,这会使用已弃用的Math.fraction(2.56).split("/")
,因此在某些浏览器中可能不兼容。
测试here