在JavaScript中,是否有任何方式为十进制数(如转换0.0002
),以表示为一个字符串(例如“一小部分2/10000"
)?
如果调用的函数decimalToFraction
已经为这个目的编写的,然后decimalToFraction(0.0002)
将返回字符串"2/10000"
。
在JavaScript中,是否有任何方式为十进制数(如转换0.0002
),以表示为一个字符串(例如“一小部分2/10000"
)?
如果调用的函数decimalToFraction
已经为这个目的编写的,然后decimalToFraction(0.0002)
将返回字符串"2/10000"
。
您可以使用埃里克·加里森fraction.js库做到这一点,更多的分数操作。
var f = new Fraction(2, 10000);
console.log(f.numerator + '/' + f.denominator);
要做到0.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/
看来工作:
http://jsfiddle.net/VKfHH/
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去无缘无故。
使用数字0.56的小数部分
有2位在0.56,写出0.56为56/100。
因此,我们有2 + 56/100号,需要由双方分割的分子和分母,以减少这部分到最低条款最大公约数 ,也就是4在这种情况下。
所以,这部分减少到最低条件是2 + 14/25。
要添加这些全2,我们通过除数乘法和加法到14
(2 * 25 + 14)/ 25 =25分之64
是否尝试过这样的事情?
<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>
我做了什么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 "";
}
}
这可能是有点老了,但被张贴代码失败上我有固定的错误,将发布以下更新的代码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;
}
}
我只想留一个替代方案,我发现将十进制数转换成分数和分数减少 ,这是一个JS库。
库调用fraction.js ,这对我来说非常有帮助,节省了我很多时间和精力。 希望能对别人有用!
我知道这是一个老问题,但我已经创建了已经大大简化的功能。
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("/")
用于容纳所述分子和分母的阵列) 请注意,这使用的是弃用arguments.callee
,因而可能会在某些浏览器不兼容。
测试它在这里