If the string value contains parsing float and formats it otherwise returns a string

I am working with an API that returns nothing but strings in a response. I need to format any decimal value returned in a string to have a leading zero, but without trailing zeros. If the value is something other than a float in a string, it should be returned without 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 a float, so I did it below. Param points - 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 does when the value is a decimal string, but just returns the entered value if the string does not contain a float? As a side, I use Angular and will eventually make it a filter.

+4
source share
1 answer

UPDATE # 2

Also from fooobar.com/questions/13635 / ...

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

So, at the end you can check if there is isFloat, then isInt, then conclude that this is a string.

As you said (comment) in the case of "7.0":

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

UPDATE

Actually there is no need for a function numberFormat:

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

Take the following functions:

function isFloat(n) {
  n = parseFloat(n);
  // from /questions/13635/how-do-i-check-that-a-number-is-float-or-integer/98340#98340
  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);
+1
source

Source: https://habr.com/ru/post/1616105/


All Articles