Reputation: 175
I have a problem. Script parsing csv to html. But number is read as a string. How can I add "0" to numbers that do not have to decimals. For example:
15,45
12,00
14,2
14,54
I want to add 0 to all numbers like 4,2
15,45
12,00
14,20
14,54
Upvotes: 0
Views: 102
Reputation: 67505
If you get all strings as posted format in the OP you could use length :
["15,45","12,00","14,2"].forEach(function(v){
alert(v.split(',')[1].length==1?v+"0":v);
})
Upvotes: 1
Reputation: 123377
In vanillaJS
var num = "14,2";
/* string to number conversion */
num = +(num.replace(',','.'));
/* set 2 digits after decimal point */
num = num.toFixed(2);
/*
Input Output
--------------
14,25 14.25
14,2 14.20
14 14.00 */
Reduced in a single statement, as suggested in the comments below:
(+num.replace(',','.')).toFixed(2);
if you have an array of strings you could easily convert them using Array.map()
var nums = ["14", "14,2", "14,25"];
nums = nums.map(n => (+n.replace(',','.')).toFixed(2));
// => ["14.00", "14.20", "14.25"]
Upvotes: 2
Reputation: 74738
You can use this:
var arr = ["15,45","12,00","14,2","14,54"];
var newarr = arr.map(function(o){
var val = o.split(',');
return val[1].length == 1 ? val.join(',')+"0" : val.join(',');
});
document.querySelector('pre').innerHTML = JSON.stringify(newarr, 0, 4);
<pre></pre>
Upvotes: 0
Reputation: 68393
Try
var output = "15,2".split(",").map(function(val){ return val > 100 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
var output = "15,100".split(",").map(function(val){ return val > 99 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
var output = "15,".split(",").map(function(val){ return val > 100 ? val: (val+"00").slice(0,2);}).join(",");
alert(output);
Upvotes: 2