Reputation: 19
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
Upvotes: 1
Views: 11514
Reputation: 704
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');
Upvotes: 0
Reputation: 44087
Because you're converting it back into a number:
var val = 10;
val = val.toFixed(2);
val = +val;
console.log(val);
Upvotes: 2
Reputation: 1
Please put value in double quote so it consider as string.
var val= "10";
val= parseFloat(val).toFixed(2);
console.log(val);
Upvotes: 0
Reputation: 5742
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
Upvotes: 0
Reputation: 3802
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);
Upvotes: 1