4

I'm working with an API that returns nothing but strings in the response. I need to format any decimal value returned in the string to have a leading zero but no trailing zeros. If the value is anything other than a float in the string it should be returned with out any formatting changes.

Example: if the value is ".7", ".70" or "0.70" my function will always return "0.7". If the value is "1+" it will return "1+".

Initially I thought the API was returning floats so I was doing this below. The places param is how many decimal places to display.

function setDecimalPlace(input, places) {
    if (isNaN(input)) return input;
    var factor = "1" + Array(+(places > 0 && places + 1)).join("0");

    return Math.round(input * factor) / factor;
};

How can I accomplish what the above function is doing when the value is a decimal string, but just return the inputed value if the string does not contain a float? As an aside I'm using Angular and will end up making this a filter.

Stavros_S
  • 2,145
  • 7
  • 31
  • 75
  • Possible duplicate of [How can I use an AngularJS filter to format a number to have leading zeros?](http://stackoverflow.com/questions/17648014/how-can-i-use-an-angularjs-filter-to-format-a-number-to-have-leading-zeros) – Mikko Viitala Nov 16 '15 at 17:59
  • That question was not really dealing with string values and was only handling leading zeros. – Stavros_S Nov 16 '15 at 18:23

1 Answers1

1

UPDATE #2

Also from https://stackoverflow.com/a/3886106/4640499

function isInt(n) {
   return n % 1 === 0;
}

So at the end you could check if isFloat then isInt then conclude that it's a String.

As you said (comment) in case of '7.0':

var v = '7.0';
var formatted = (isFloat(v) || isInt(parseFloat(v))) ? parseFloat(v) : v;

UPDATE

Actually, there's no need of numberFormat function:

var v = '.7';
if(isFloat(v)) var formatted = parseFloat(v);

Take these functions:

function isFloat(n) {
  n = parseFloat(n);
  // from https://stackoverflow.com/a/3886106/4640499
  return n === Number(n) && n % 1 !== 0;
}
function numberFormat(e, t, n, o) {
  // from http://phpjs.org/functions/number_format/
  var r = e,
    u = isNaN(t = Math.abs(t)) ? 2 : t,
    c = void 0 == n ? '.' : n,
    a = void 0 == o ? ',' : o,
    l = 0 > r ? '-' : '',
    d = parseInt(r = Math.abs(+r || 0).toFixed(u)) + '',
    s = (s = d.length) > 3 ? s % 3 : 0
  ;
  return l + (s ? d.substr(0, s) + a : '') +
    d.substr(s).replace(/(\d{3})(?=\d)/g, '$1' + a) +
    (u ? c + Math.abs(r - d).toFixed(u).slice(2) : '');
}
function formatFloat(e) {
  return numberFormat(e, 1);
}

And then:

var v = '.7';
console.info(isFloat(v));
console.info(formatFloat(v));

if(isFloat(v)) formatFloat(v);
Community
  • 1
  • 1
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
  • Great solution! One question, in the case of a number coming in as 7.0 would it be best to parse that out at the string level or following the parseFloat in your update? – Stavros_S Nov 16 '15 at 20:26