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);
return n === Number(n) && n % 1 !== 0;
}
function numberFormat(e, t, n, o) {
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);
source
share