2014-03-03 36 views
1

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
+0

我建议从字符串末尾往后走,并确定这个值。也许从http://stackoverflow.com/questions/1966476/javascript-process-each-letter-of-text开始吧? – Metalskin

+1

基于描述,我期望你的最后一个例子是34.234。你是怎么想出34.34的? – Timeout

+0

有234w所以应该避免。 –

回答

5

一个相当直接的解决方法:

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]); 
} 
+0

我不认为前面的*?= *是必需的,'parseFloat(s.match(/ \ d +(\。| $)/ g).slice(-2).join(''))'是足够。小数位可以留在匹配中,尾部点由* parseFloat *修剪。 – RobG

+0

@RobG好的,谢谢。 –

+0

我不明白'\ d +(\。| $)'中的'(\。| $)'如何匹配'xx.yy'中的'yy' –

0

下面将做你想要的(我假设最后一个应该返回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; 
} 
+0

由于最后一位数字(.234w)包含一个字母,因此它似乎是最后一次返回* 34.34 *,所以使用了前两组数字。否则''parseFloat(s.match(/ \ d + \。[^ \。] + $ /))'会做。 – RobG

+0

啊,有道理。在问题中不清楚:-) – Metalskin

+0

是的,事实并非如此。 ;-) – RobG