将分数字符串转换为十进制? [英] Convert Fraction String to Decimal?
本文介绍了将分数字符串转换为十进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个javascript函数,它可以采用分数输入字符串,例如'3/2'
并将其转换为十进制 - 或者作为字符串'1.5'
或数字 1.5
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;
});
有办法吗?
推荐答案
由于还没有人提及它,因此有一个快速而肮脏的解决方案:
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.
这篇关于将分数字符串转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文