var fNum = parseFloat("32.23.45");
結果在32.23,但我需要從去年小數點的字符串:23.45如何獲得特定的最後十進制浮點值
例如,下面的字符串應該返回以下值:
- 「12.234 .43.234" - > 43.234,
- 「345.234.32.34」 - > 32.34和
- 「234.34.34.234w」 - > 34.34
var fNum = parseFloat("32.23.45");
結果在32.23,但我需要從去年小數點的字符串:23.45如何獲得特定的最後十進制浮點值
例如,下面的字符串應該返回以下值:
一個相當直接的解決方法:
function toFloat(s) {
return parseFloat(s.match(/\d+(\.|$)/g).slice(-2).join('.'));
}
例如:
toFloat("32.23.45") // 23.45
toFloat("12.234.43.234") // 43.234
toFloat("345.234.32.34") // 32.34
toFloat("234.34.34.234w") // 34.34
更新:這裏有一個替代版本,這將更加有效地處理與中混有非數字的字符串
function toFloat(s) {
return parseFloat(s.match(/.*(\.|^)(\d+\.\d+)(\.|$)/)[2]);
}
我不認爲前面的*?= *是必需的,'parseFloat(s.match(/ \ d +(\。| $)/ g).slice(-2).join(''))'是足夠。小數位可以留在匹配中,尾部點由* parseFloat *修剪。 – RobG
@RobG好的,謝謝。 –
我不明白'\ d +(\。| $)'中的'(\。| $)'如何匹配'xx.yy'中的'yy' –
下面將做你想要的(我假設最後一個應該返回34.234,而不是34.24)。
alert (convText("12.234.43.234"));
alert (convText("345.234.32.34"));
alert (convText("234.34.34.234w"));
function convText(text) {
var offset = text.length - 1;
var finished = false;
var result = '';
var nbrDecimals = 0;
while(!finished && offset > -1) {
if(!isNaN(text[offset]) || text[offset] === '.') {
if(text[offset] === '.') {
nbrDecimals++;
}
if(nbrDecimals > 1) {
finished = true;
} else {
result = text[offset] + result;
}
}
offset--;
}
return result;
}
我建議從字符串末尾往後走,並確定這個值。也許從http://stackoverflow.com/questions/1966476/javascript-process-each-letter-of-text開始吧? – Metalskin
基於描述,我期望你的最後一個例子是34.234。你是怎麼想出34.34的? – Timeout
有234w所以應該避免。 –