如何将“1 1/4”转换为 1.25?
我想获取用户输入并将其转换为等价的逻辑数字。我说逻辑是因为 2 R 和 R 2 需要为 2(与测量脊椎按摩调整有关)。一切都有效,直到他们需要能够使用带分数。
有这个库吗?
唯一不起作用的数字是“1 1/4”,它被错误地转换为“2.75”。
// Sample input
var values = ["2.5", "1 1/4", "1/4", "2 R", "R 2"];
function l(msg) {
console.log(msg)
}
function toDecimal(x) {
if (x.indexOf('/') != -1) {
var parts = x.split(" ")
var decParts = parts[1].split("/")
return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
} else {
return x
}
}
function total_it_up(values){
var total = 0,
value = 0
if(values === undefined)
return 0
$.each(values, function(index, value){
value = value.replace(/[^0-9./]+/g, "")
value = eval(value)
l(value)
total += parseFloat(value)
})
return total
}
解决方案
function toDecimal(x) {
if (x.indexOf('/') != -1) {
var parts = x.split(" ")
var decParts;
if (parts.length > 1) {
decParts = parts[1].split("/");
}
else {
decParts = parts[0].split("/");
parts[0] = 0;
}
return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
} else {
return x
}
}
function total_it_up(values){
var total = 0;
if(values === undefined)
return 0;
$.each(values, function(index, value){
total += parseFloat(toDecimal($.trim(value.replace(/[^0-9./ ]+/g, ""))));
})
return total;
}
最佳答案
我们没有看到任何对 toDecimal() 的调用,因此我假设 $.each
循环在您的原始代码中调用它。如果是这种情况,那么 1 1/4 将变为 2.75,因为正则表达式会删除 1 和 1/4 之间的空格,结果是 11/4,即 2.75。允许空格,但 $.trim
结果,以便删除任何前导或尾随空格。您也不应该使用eval()
。
关于javascript - 如何将带分数转换为小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13200347/