简体   繁体   English

如何使用给定格式格式化数字字符串?

[英]How can I format a numeric string with the given format?

I need to create a function which take a format string and a numeric string and output the numeric string in the given format. 我需要创建一个接受格式字符串和数字字符串并以给定格式输出数字字符串的函数。

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

I want my function to output 1,234.50 我希望我的功能输出1,234.50

Till now I got this much 直到现在我得到了这么多

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

But it is not that accurate? 但这不准确吗? Is there a better way to do this in pure javascript? 有没有更好的方法可以用纯JavaScript做到这一点?

Edit: The format string may vary "###,##.#" or "##,###.###" etc 编辑:格式字符串可能会变化“ ###,##。#”或“ ##,###。###”等

Take a look at javascript-number-formatter . 看看javascript-number-formatter It may meet your needs. 它可能满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM