1

var fNum = parseFloat("32.23.45"); results in 32.23 but I need the string from last decimal point: 23.45

For example, the following strings should return the following values:

  • "12.234.43.234" -> 43.234,
  • "345.234.32.34" -> 32.34 and
  • "234.34.34.234w" -> 34.34
Metalskin
  • 3,998
  • 5
  • 37
  • 61
Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68
  • I would suggest walking backwards from the end of the string and determine the value that way. Maybe start with http://stackoverflow.com/questions/1966476/javascript-process-each-letter-of-text as a guide? – Metalskin Mar 03 '14 at 02:51
  • 1
    Based on the description I would expect your last example to be 34.234. How did you come up with 34.34? – Timeout Mar 03 '14 at 03:01
  • there is 234w so it should be avoided. – Navin Rauniyar Mar 03 '14 at 03:10

2 Answers2

5

A fairly direct solution:

function toFloat(s) { 
    return parseFloat(s.match(/\d+(\.|$)/g).slice(-2).join('.')); 
}

For example:

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

Update: Here's an alternative version which will more effectively handle strings with non-digits mixed in.

function toFloat(s) { 
    return parseFloat(s.match(/.*(\.|^)(\d+\.\d+)(\.|$)/)[2]); 
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • I don't think the look ahead *?=* is required, `parseFloat(s.match(/\d+(\.|$)/g).slice(-2).join(''))` is sufficient. The decimal place can be left in the match, a trailing dot is trimmed by *parseFloat*. – RobG Mar 03 '14 at 03:25
  • I don't understand how the `(\.|$)` in `\d+(\.|$)` can match the `yy` in `xx.yy` – Royi Namir Mar 03 '14 at 03:52
  • @RoyiNamir Basically, it means the digits must be followed by a `.` (`\.`) or the end of the string (`$`). I used that to ensure that there are no non-digits in that group. – p.s.w.g Mar 03 '14 at 03:57
0

The following will do exactly what you would like (I'm presuming that the last one should return 34.234, not 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;
}
Metalskin
  • 3,998
  • 5
  • 37
  • 61
  • It seems the last returns *34.34* because the last sequence of digits (.234w) contains a letter, so the previous two sets of digits are used. Otherwise `parseFloat(s.match(/\d+\.[^\.]+$/))` would do. – RobG Mar 03 '14 at 03:17