Reputation: 129
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
Upvotes: 0
Views: 309
Reputation: 3050
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.
Upvotes: 0
Reputation: 2038
var a = ["5.0", 2.25, 3.0, "4.0"];
a.map(function(b){
return parseFloat(b).toFixed(1)
})
Upvotes: 0
Reputation: 65806
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));
});
Upvotes: 0
Reputation: 32145
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);
Upvotes: 2
Reputation: 6366
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);
Upvotes: 0