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