将分数字符串转换为小数?
我正在尝试创建一个 JavaScript 函数,它可以接受分数输入字符串,例如 '3/2'
并将其转换为十进制 - 或者作为字符串 '1.5'
或数字 1.5
function ratio(fraction) {
var fraction = (fraction !== undefined) ? fraction : '1/1',
decimal = ??????????;
return decimal;
});
有办法做到这一点吗?
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
function ratio(fraction) {
var fraction = (fraction !== undefined) ? fraction : '1/1',
decimal = ??????????;
return decimal;
});
Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
由于还没有人提到它,所以有一个快速而肮脏的解决方案:
它具有正确评估各种数学字符串的好处。
这里的人们很快就会提到使用原始评估的危险,但我将其作为懒人的答案提交。
Since no one has mentioned it yet there is a quick and dirty solution:
Which has the perks of correctly evaluating all sorts of mathematical strings.
People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.
以下是执行此操作所需的最基本的代码:
JsFiddle: http://jsfiddle.net/XS4VE/
需要考虑的事项:
Here is the bare bones minimal code needed to do this:
JsFiddle: http://jsfiddle.net/XS4VE/
Things to consider:
我有一个函数用来处理整数、混合分数(包括 unicode 粗俗分数字符)和小数。可能需要一些改进,但它适合我的目的(食谱成分列表解析)。
输入
"2 1/2"
,"2½"
," 2 ½"
和"2.5"
都将返回2.5
。示例:它不处理的一件事是分数内的小数,例如
“2.5 / 5”
。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).
Inputs
"2 1/2"
,"2½"
,"2 ½"
, and"2.5"
will all return2.5
. Examples:One thing it doesn't handle is decimals within the fraction, e.g.
"2.5 / 5"
.像这样的东西:
Something like this:
我创建了一个很好的函数来做到这一点,一切都基于这个问题和答案,但它将获取字符串并输出十进制值,但也会输出整数,并且不会出现错误
https://gist.github.com/drifterz28/6971440
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
为时已晚,但可能会有所帮助:
您可以使用
Array.prototype.reduce
而不是eval
https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
ES6
CJS
[编辑] 删除了减速器初始值,现在该函数适用于大于 1 的分子。谢谢,James福瑞。
Too late, but can be helpful:
You can use
Array.prototype.reduce
instead ofeval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
ES6
CJS
[EDIT] Removed reducer initial value and now the function works for numerators greater than 1. Thanks, James Furey.
函数 (ES6):
函数(ES6,压缩):
示例:
Function (ES6):
Function (ES6, condensed):
Examples:
使用现代解构语法,最好/最安全的答案可以简化为:
换句话说,通过
/
符号拆分派系,将两个结果字符串转换为数字,然后返回第一个数字除以第二个数字......全部只有两行(非常可读的)代码。
编辑
以上假设对于
1.5
,您只会得到3/2
...而不是1 1/2
>。但是,正如 @Aro Parada 在评论中指出的那样,您可能需要处理这样的整数。如果是这样,您可以使用非常相似的基于
split
的方法,但使用reverse
来处理我们有时只有整数的事实:您甚至可能不需要那里的
trim
;像1 1/2
这样的字符串即使没有它也能工作,但如果你可以有1 1/2
你会想要保留trim
。With modern destructuring syntax, the best/safest answer can be simplified to:
In other words, split the faction by its
/
symbol, turn both resulting strings into numbers, then return the first number divided by the second ...... all with only two (very readable) lines of code.
EDIT
The above assumes that for
1.5
you will only get3/2
... and not1 1/2
. But, as @Aro Parada noted in a comment, you might need to handle such whole numbers.If so, you could use a very similar
split
-based approach, but with areverse
to handle the fact that we only sometimes have a whole number:You might not even need the
trim
in there; strings like1 1/2
will work even without it, but if you can have1 1/2
you'll want to keep thetrim
.如果您不介意使用外部库,math.js 提供了一些有用的函数将分数转换为小数以及执行分数算术。
If you don't mind using an external library, math.js offers some useful functions to convert fractions to decimals as well as perform fractional number arithmetic.
从可读性、逐步调试的角度来看,这可能更容易理解:
From a readability, step through debugging perspective, this may be easier to follow:
要将分数转换为小数,只需将顶部数字除以底部数字即可。 5 除以 3 等于 5/3 或 1.67。非常喜欢:
希望这有帮助,哈哈
To convert a fraction to a decimal, just divide the top number by the bottom number. 5 divided by 3 would be 5/3 or 1.67. Much like:
Hope this helps, haha
它与 eval() 方法一起使用,但您可以使用 parseFloat 方法。我觉得这样更好!
不幸的是,它只适用于这种值 - “12.2”而不适用于“5/8”,但由于您可以处理计算,我认为这是一个很好的方法!
It works with eval() method but you can use parseFloat method. I think it is better!
Unfortunately it will work only with that kind of values - "12.2" not with "5/8", but since you can handle with calculation I think this is good approach!
如果您想将结果用作分数,而不仅仅是从字符串中获取答案,则可以使用 https: //github.com/infusion/Fraction.js 可以很好地完成这项工作。
If you want to use the result as a fraction and not just get the answer from the string, a library like https://github.com/infusion/Fraction.js would do the job quite well.
虽然有点晚了,但安全问题较少(至少根据 MDN)的
eval()
的替代方案是Function()
工厂。这将在控制台中输出结果“1.5”。
还请注意:像 1 1/2 这样的混合分数既不能与
eval()
一起使用,也不能与Function()
的解决方案一起使用当他们俩偶然发现这个空间时写下的。Also a bit late to the party, but an alternative to
eval()
with less security issues (according to MDN at least) is theFunction()
factory.This would output the result "1.5" in the console.
Also as a side note: Mixed fractions like 1 1/2 will not work with neither
eval()
nor the solution withFunction()
as written as they both stumble on the space.更安全的 eval() 根据 MDN
https:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!
safer eval() according to MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!
这也行得通:
This too will work:
我开发了一个函数,使用可以作为整数或小数分数传递的因子来转换值。用户输入和转换因子的格式可能不正确,因此它会检查原始值是否为数字,以及转换是否可以转换为分数,假设 /number 表示 1/number,或者有分子和分母,格式为数字/数字。
I developed a function to convert a value using a factor that may be passed as a fraction of integers or decimals. The user input and conversion factor might not be in the correct format, so it checks for the original value to be a number, as well as that the conversion can be converted to a fraction assuming that /number means 1/number, or there are a numerator and a denominator in the format number/number.
您可以将 eval() 与正则表达式结合使用来实现计算分数的安全方法
You can use eval() with regex to implement a secure method to calculate fraction