2015-07-19 90 views
0

我需要创建一个函数,它采用格式字符串和数字字符串,并以给定格式输出数字字符串。如何格式化给定格式的数字字符串?

var format = "##,###.##";//The format string may vary "###,##.#" etc 
var number = "1234.5"; 

我希望我的函数输出1,234.50

直到现在我得到这么多

String.prototype.replaceAt=function(index, character) { 
    return this.substr(0, index) + character + this.substr(index+character.length); 
} 
String.prototype.insert = function (index, string) { 
    if (index > 0) 
    return this.substring(0, index) + string + this.substring(index, this.length); 
    else 
    return string + this; 
}; 
function formatString(format,number) { 
    var numeric = number.split(".")[0]; 
    var decimal = number.split(".")[1]; 
    var numericFormat = format.split(".")[0]; 
    numeric = numeric.split("").reverse().join(""); 
    numericFormat = numericFormat.split("").reverse().join(""); 
    for (var i = 0, len = numeric.length; i < len; i++) { 
     if(numericFormat[i] === ',') { 
      numeric = numeric.insert(i, ','); 
      console.log(numeric); 
     } 
    } 
    numeric = numeric.split("").reverse().join(""); 
    console.log(numeric); 
    numeric = numeric + "."+ decimal; 
    return numeric; 
} 

但它是不是准确?有没有更好的方式在纯JavaScript中做到这一点?

编辑:格式字符串可能会有所不同 “###,###” 或 “##,###。###。” 等

+0

[Javascript Thousand Separator/string format]可能重复(http://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format) – Emissary

回答