Priyanka Kumari
Priyanka Kumari

Reputation: 19

Converting a string into decimal number in JavaScript

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

Answers (5)

eustatos
eustatos

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

Jack Bashford
Jack Bashford

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

sagar sonawane
sagar sonawane

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

Chanaka Weerasinghe
Chanaka Weerasinghe

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

Hardik Leuwa
Hardik Leuwa

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

Related Questions