简体   繁体   中英

How to convert a string of numbers in array

a = ["5.0", 2.25, 3.0, "4.0"] how to get a = [5.0, 2.25, 3.0, 4.0].

I can able to get a = [5, 2.25, 3, 4]. but i need like this [5.0, 2.25, 3.0, 4.0]

can any one help me. please,

Thanks

Well simply map the result of Number :

 var a = ["5.0", "2.25", "3.0", "4.0"]; var b = a.map(Number); console.log(b); 

Note:

You can't preserve the 0 from 5.0 in a Number , it won't be a valid number.

You can use .toFixed(1) to preserve it, but the results will be strings:

var b = a.map(function(v){
    return Number(v).toFixed(1);
});

Demo:

 var a = ["5.0", "2.25", "3.0", "4.0"]; var b = a.map(function(v){ return Number(v).toFixed(1); }); console.log(b); 

Map the values with a parsing call:

 var a = ["5.0", 2.25, 3.0, "4.0"]; var b = a.map(function(c) { return parseFloat(c.toString()); }); console.log(b); 

All numbers in JavaScript are floating point numbers, but when there is no decimal component, the runtime doesn't bother showing the decimal because, for example, 5.0 is exactly the same value as 5 .

If you really want to see the numbers with this decimal, you can convert them back to strings (for display) and control the precision with the .toFixed() method, which operates on a number, but returns a string:

 var a = ["5.0", 2.25, 3.0, "4.0"]; var b = a.map(Number); b.forEach(function(num){ console.log(num.toFixed(2)); }); 

var a = ["5.0", 2.25, 3.0, "4.0"];

a.map(function(b){
    return parseFloat(b).toFixed(1)
})

Basically Javascript does not return any value after decimal point if value is 0. You need to do it with programatically.

You can parse string with parseFloat and then you can use this function .toFixed() or .toString() so that it will give numbers with decimal point, even if 0 after decimal point.

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