简体   繁体   中英

How can I add some number to string in javascript or jquery

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

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

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"]

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

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> 

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