1

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
3
  • 5
    10.00 is same as 10 it doesn't makes sense to keep .00 in number, you need to keep it as string if you want 10.00 Commented Jun 27, 2019 at 4:13
  • Please, also check the handling of decimals at w3schools.com/jsref/jsref_parsefloat.asp Commented Jun 27, 2019 at 4:16
  • JS numbers don't have a format associated with them. 10 is the same as 10.0 the same as 10.00 the same as 10.000 so on display, it just automatically drops any extra digits. If you want a number formatted, you have to use a string. Commented Jun 27, 2019 at 4:38

5 Answers 5

2

Because you're converting it back into a number:

var val = 10;
val = val.toFixed(2);
val = +val;
console.log(val);

Sign up to request clarification or add additional context in comments.

1 Comment

toFixed() returns string value. But i want into decimal number .
1

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);

1 Comment

Why you're adding jQuery when you're not even using it mate ¯\_(ツ)_/¯
0

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

2 Comments

Please open this link : -- plnkr.co/edit/Hk51lG8xwUnGKc1orIDL?p=preview I have executed your code in above link. You can see there output that is coming in string.
plunker that shows string so put this derectly parseFloat(dec) . document.getElementById("demo").innerHTML = typeof parseFloat(dec);
0

Please put value in double quote so it consider as string.

var val= "10";
val= parseFloat(val).toFixed(2);
console.log(val);

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.