简体   繁体   中英

Converting a string into decimal number in JavaScript

If I have a string (ie "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); 

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM