If I have a string (i.e "10.00"), how do I convert it into decimal number? My attempt is below:
var val= 10;
val = val.toFixed(2);
val= Number(val); // output 10 and required output 10.00
Because you're converting it back into a number:
var val = 10;
val = val.toFixed(2);
val = +val;
console.log(val);
You can use parseFloat() to convert string to float number and can use toFixed() to fix decimal points
var val = "10.00";
var number = parseFloat(val).toFixed(2);
console.log(number);
jQuery when you're not even using it mate ¯\_(ツ)_/¯simplest way
var val= 10;
var dec=parseFloat(Math.round(val * 100) / 100).toFixed(2)
print(typeof dec )
print("decimal "+dec)
output number decimal 10.00
document.getElementById("demo").innerHTML = typeof parseFloat(dec);You can use Intl.NumberFormat
But be careful - it is not supported Safari.
function customFormatter(digit) {
if (typeof digit === 'string') {
digit = parseFloat(digit);
}
var result = new Intl.NumberFormat('en-En', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(digit)
return result;
}
console.assert(
customFormatter(10) === '10.00',
{msg: 'for 10 result must be "10.10"'}
);
console.assert(
customFormatter('10') === '10.00',
{msg: 'for 10 result must be "10.10"'}
);
console.log('All tests passed');
10.00is same as10it doesn't makes sense to keep.00in number, you need to keep it as string if you want10.0010is the same as10.0the same as10.00the same as10.000so on display, it just automatically drops any extra digits. If you want a number formatted, you have to use a string.