0

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

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?

Edit: The format string may vary "###,##.#" or "##,###.###" etc

Damodaran
  • 10,882
  • 10
  • 60
  • 81
  • possible duplicate of [Javascript Thousand Separator / string format](http://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format) – Emissary Jul 19 '15 at 12:59

1 Answers1

-1

Take a look at javascript-number-formatter. It may meet your needs.

Ed Ballot
  • 3,405
  • 1
  • 17
  • 24