任何人都可以建议我如何将给定的Tick格式编号转换为十进制JavaScript?
Tick Format Decimal
10-8 10+8/32 == 10.25
10-16/32 10+ 16/32 == 10.50
10-8+ 10 + 8/32 + 1/64 == 10.265625
格式由整数部分组成,后跟' - '然后是以1/32的倍数(称为引用)指定的小数部分。可以选择' +'最后表示半引用(1/64)。由于我是JS的初学者,如果有人可以提出基本想法(不是全长代码)来开始,那将是一个很好的帮助。
由于
答案 0 :(得分:1)
这是使用RegExp执行此操作的方法:
// the tick format values
var array = ["10-8", "10-16/32", "10-8+"];
// regular expressions to check for the matches
var regexes = [/^\d+?-\d+?$/m, /^\d+?-\d+?\/\d+$/m, /^\d+?-\d+?\+$/m];
// this is where the decimal format values will go
var converted = [];
// loop through the array 'array'
for (i = 0; i < array.length; i++) {
// for each string in array loop through the array 'regexes'
for (r = 0; r < regexes.length; r++) {
// Check if any regex matches
if (regexes[r].exec(array[i])) {
// get the first digit
var x = parseInt(/^(\d+)-/m.exec(array[i])[1]);
// get the second digit
var y = parseInt(/-(\d+)\.*/m.exec(array[i])[1]);
// if the regex is last add 1 / 64 else don't
if (r == 2) {
converted.push(x + (y / 32) + (1 / 64));
} else {
converted.push(x + (y / 32));
}
}
}
}
// finally log the new array 'converted' which contains the decimal format to the console
console.log(converted)
答案 1 :(得分:1)
我会这样做:
function decTick(str) {
var toReturn = 0;
var splitted = str.split('-');
toReturn += splitted[0]*1;
if (splitted.length>1) {
if ( splitted[1].substring(splitted[1].length-1)=="+" ) {
toReturn += 1/64;
splitted[1] = splitted[1].replace('+','');
};
var fractional = splitted[1].split('/');
toReturn += fractional[0]/32;
};
return toReturn;
};
console.log( decTick('10-8') );
console.log('-----------------------------');
console.log( decTick('10-16/32') );
console.log('-----------------------------');
console.log( decTick('10-8+') );
console.log('-----------------------------');
输出:
10.25
-----------------------------
10.5
-----------------------------
10.265625
-----------------------------
答案 2 :(得分:1)
这可能是最短的解决方案,转换为等式,而不是用eval()
计算:
function decTick(str) {
return eval( str.replace(/\-([1-9]+)$/, '-$1/32').replace('+', '+1/64').replace('-', '+').replace(/\+(\d+)\+/, '+$1/32+') );
};
console.log( decTick('10-8') );
console.log('-----------------------------');
console.log( decTick('10-16/32') );
console.log('-----------------------------');
console.log( decTick('10-8+') );
console.log('-----------------------------');
console.log( decTick('10-16/32+') );
console.log('-----------------------------');
按预期输出:
10.25
-----------------------------
10.5
-----------------------------
10.265625
-----------------------------
10.515625
-----------------------------