Navin Rauniyar
Navin Rauniyar

Reputation: 10525

how to get specific last decimal float value

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:

Upvotes: 1

Views: 96

Answers (2)

Metalskin
Metalskin

Reputation: 4268

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;
}

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149010

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

Upvotes: 5

Related Questions