Javascript 将分数字符串转换为十进制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7142657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Fraction String to Decimal?
提问by ryanve
I'm trying to create a javascript function that can take a fraction input string such as '3/2'
and convert it to decimal—either as a string '1.5'
or number 1.5
我正在尝试创建一个 javascript 函数,该函数可以采用分数输入字符串,例如'3/2'
并将其转换为十进制 - 作为字符串'1.5'
或数字1.5
function ratio(fraction) {
var fraction = (fraction !== undefined) ? fraction : '1/1',
decimal = ??????????;
return decimal;
});
Is there a way to do this?
有没有办法做到这一点?
回答by Akinos
Since no one has mentioned it yet there is a quick and dirty solution:
由于没有人提到它,因此有一个快速而肮脏的解决方案:
var decimal = eval(fraction);
Which has the perks of correctly evaluating all sorts of mathematical strings.
它具有正确评估各种数学字符串的好处。
eval("3/2") // 1.5
eval("6") // 6
eval("6.5/.5") // 13, works with decimals (floats)
eval("12 + 3") // 15, you can add subtract and multiply too
People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.
这里的人们会很快提到使用原始 eval 的危险,但我将此作为懒人的答案提交。
回答by Matt Greer
Here is the bare bones minimal code needed to do this:
这是执行此操作所需的最少代码:
var a = "3/2";
var split = a.split('/');
var result = parseInt(split[0], 10) / parseInt(split[1], 10);
alert(result); // alerts 1.5
JsFiddle: http://jsfiddle.net/XS4VE/
JsFiddle:http: //jsfiddle.net/XS4VE/
Things to consider:
需要考虑的事项:
- division by zero
- if the user gives you an integer instead of a fraction, or any other invalid input
- rounding issues (like 1/3 for example)
- 被零除
- 如果用户给你一个整数而不是一个分数,或者任何其他无效的输入
- 舍入问题(例如 1/3)
回答by Coomie
Something like this:
像这样的东西:
bits = fraction.split("/");
return parseInt(bits[0],10)/parseInt(bits[1],10);
回答by E-comm
I created a nice function to do just that, everything was based off of this question and answers but it will take the string and output the decimal value but will also output whole numbers as well with out errors
我创建了一个很好的函数来做到这一点,一切都基于这个问题和答案,但它会接受字符串并输出十进制值,但也会输出整数而没有错误
https://gist.github.com/drifterz28/6971440
https://gist.github.com/drifterz28/6971440
function toDeci(fraction) {
fraction = fraction.toString();
var result,wholeNum=0, frac, deci=0;
if(fraction.search('/') >=0){
if(fraction.search('-') >=0){
wholeNum = fraction.split('-');
frac = wholeNum[1];
wholeNum = parseInt(wholeNum,10);
}else{
frac = fraction;
}
if(fraction.search('/') >=0){
frac = frac.split('/');
deci = parseInt(frac[0], 10) / parseInt(frac[1], 10);
}
result = wholeNum+deci;
}else{
result = fraction
}
return result;
}
/* Testing values / examples */
console.log('1 ',toDeci("1-7/16"));
console.log('2 ',toDeci("5/8"));
console.log('3 ',toDeci("3-3/16"));
console.log('4 ',toDeci("12"));
console.log('5 ',toDeci("12.2"));
回答by Jake Boone
I have a function I use to handle integers, mixed fractions (including unicode vulgar fraction characters), and decimals. Probably needs some polishing but it works for my purpose (recipe ingredient list parsing).
我有一个用于处理整数、带分数(包括 unicode 粗略分数字符)和小数的函数。可能需要一些改进,但它适用于我的目的(配方成分列表解析)。
Inputs "2 1/2"
, "2?"
, "2 ?"
, and "2.5"
will all return 2.5
. Examples:
输入"2 1/2"
、"2?"
、"2 ?"
和"2.5"
都将返回2.5
。例子:
var numQty = require("numeric-quantity");
numQty("1 1/4") === 1.25; // true
numQty("3 / 4") === 0.75; // true
numQty("?" ) === 0.25; // true
numQty("2?") === 2.5; // true
numQty("?") === 0.75; // true
numQty("?") === 0.333; // true
numQty("?") === 0.667; // true
One thing it doesn't handle is decimals within the fraction, e.g. "2.5 / 5"
.
它不处理的一件事是分数中的小数,例如"2.5 / 5"
.
回答by Fabricio Mendon?a
Too late, but can be helpful:
为时已晚,但可能会有所帮助:
You can use Array.prototype.reduce
instead of eval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
您可以使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceArray.prototype.reduce
代替eval
ES6
ES6
const fractionStrToDecimal = str => str.split('/').reduce((p, c) => p / c);
console.log(fractionStrToDecimal('1/4/2')); // Logs 0.125
console.log(fractionStrToDecimal('3/2')); // Logs 1.5
CJS
CJS
function fractionStrToDecimal(str) {
return str.split('/').reduce((p, c) => p / c);
}
console.log(fractionStrToDecimal('1/4')); // Logs 0.25
[EDIT] Removed reducer initial value and now the function works for numerators greater than 1. Thanks, James Furey.
[编辑] 删除了减速器初始值,现在该函数适用于大于 1 的分子。谢谢,詹姆斯·弗瑞。
回答by Alfred Waligo
If you don't mind using an external library, math.jsoffers some useful functions to convert fractions to decimals as well as perform fractional number arithmetic.
如果您不介意使用外部库,math.js提供了一些有用的函数来将分数转换为小数以及执行小数运算。
console.log(math.number(math.fraction("1/3"))); //returns 0.3333333333333333
console.log(math.fraction("1/3") * 9) //returns 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.20.1/math.js"></script>
回答by James Furey
Function (ES6):
功能(ES6):
function fractionToDecimal(fraction) {
return fraction
.split('/')
.reduce((numerator, denominator, i) =>
numerator / (i ? denominator : 1)
);
}
Function (ES6, condensed):
功能(ES6,浓缩):
function fractionToDecimal(f) {
return f.split('/').reduce((n, d, i) => n / (i ? d : 1));
}
Examples:
例子:
fractionToDecimal('1/2'); // 0.5
fractionToDecimal('5/2'); // 2.5
fractionToDecimal('1/2/2'); // 0.25
fractionToDecimal('10/5/10'); // 0.2
fractionToDecimal('0/1'); // 0
fractionToDecimal('1/0'); // Infinity
fractionToDecimal('cat/dog'); // NaN
回答by Canis
Also a bit late to the party, but an alternative to eval()
with less security issues (according to MDN at least) is the Function()
factory.
聚会也有点晚了,但eval()
安全问题较少的替代方案(至少根据 MDN)是Function()
工厂。
var fraction = "3/2";
console.log( Function("return (" + fraction + ");")() );
This would output the result "1.5" in the console.
这将在控制台中输出结果“1.5”。
Also as a side note:Mixed fractions like 1 1/2 will not work with neither eval()
nor the solution with Function()
as written as they both stumble on the space.
另外作为旁注:像 1 1/2 这样的混合分数既不适用,eval()
也不适用于Function()
书面的解决方案,因为它们都在空间上绊倒了。
回答by AverageChau
safer eval() according to MDN
根据 MDN 更安全的 eval()
const safeEval = (str) => {
return Function('"use strict";return (' + str + ")")();
}
safeEval("1 1/2") // 1.5