有人能建议我如何将给定的刻度格式数字转换为十进制唱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的初学者,如果有人能提出基本的想法(不是完整的代码)来开始,这将是一个很大的帮助。
谢谢
发布于 2014-11-14 22:36:23
使用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)发布于 2014-11-14 22:52:05
我会这样做:
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
-----------------------------发布于 2014-11-14 23:19:18
这可能是最短的解,转换成方程,而不是用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
-----------------------------https://stackoverflow.com/questions/26939593
复制相似问题