在 JavaScript 中,有没有办法将十进制数(例如0.0002
)转换为表示为字符串的分数(例如 " 2/10000"
)?
如果decimalToFraction
为此目的编写了一个被调用的函数,decimalToFraction(0.0002)
则将返回字符串"2/10000"
。
在 JavaScript 中,有没有办法将十进制数(例如0.0002
)转换为表示为字符串的分数(例如 " 2/10000"
)?
如果decimalToFraction
为此目的编写了一个被调用的函数,decimalToFraction(0.0002)
则将返回字符串"2/10000"
。
您可以使用 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);
用“十进制到分数 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"
我使用这个网站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 ]
非常老的问题,但也许有人会发现这很有用。它是迭代的,不是递归的,不需要分解
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};
};
使用数字的字符串表示有一个非常简单的解决方案
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;
}
好消息是这是可能的,但您必须将其转换为代码。
让我们毫无理由地使用 2.56。
使用数字 .56 的小数部分
.56 有 2 位数字,把 .56 写成 56/100。
所以我们有 2 + 56/100 并且需要通过将分子和分母都除以最大公约数(在这种情况下为 4)将这个分数减少到最低项。
因此,这个分数减少到最低项是 2 + 14/25。
要添加整个 2,我们乘以除数并添加到 14
(2*25 + 14)/25 = 64/25
尝试过这样的事情吗?
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);
我按照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 "";
}
}
我只想要一个我发现的将十进制数转换为分数并减少分数的替代方法,它是一个 JS 库。
该库调用fraction.js,它对我非常有帮助,并为我节省了大量时间和工作。希望对其他人有用!
这可能有点旧,但发布的代码在 0 值上失败我已修复该错误并将在下面发布更新的代码
//function to get highest common factor of two numbers (a 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
if(isNaN(whole) === true)
{
whole = "0";
}
if(isNaN(decimal) === true)
{
return ((whole==0)?"0" : whole);
}
else
{
return ((whole==0)?"0 " : whole+" ")+decimal/t+"/"+num/t;
}
}
我知道这是一个老问题,但我创建了一个大大简化的函数。
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("/")
用于包含分子和分母的数组)请注意,这使用了 deprecated arguments.callee
,因此在某些浏览器中可能不兼容。
在这里测试