0

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
gainsky
  • 177
  • 10

4 Answers4

2

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);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

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"]
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • This is the most correct and most performant answer. Maybe compete with the one-liners and write it like this: `(+num.replace(',','.')).toFixed(2);` ? – A1rPun Apr 04 '16 at 11:31
  • yes, but for clarity purpose I splitted the code in two readable (and commented) lines, I'm not doing a codegolf competition :) – Fabrizio Calderan Apr 04 '16 at 11:41
1

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);
})
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

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>
Jai
  • 74,255
  • 12
  • 74
  • 103