Andrés Montero Andrés Montero - 5 months ago 20
Javascript Question

Add dollar sign in to currency format?

This is the code I have, it returns numbers in currency format but I wish to add the dollar sign ($) before the numbers.

document.getElementById("numbers").onblur = function (){
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}


The id numbers refers to a input text

Thanks!

Answer

Use string concatentation and update your regex to replace both commas and dollar signs with an empty string. That will prevent the NaN error when you re-parse the value on another blur change.

document.getElementById("numbers").onblur = function (){    
  this.value = "$" + parseFloat(this.value.replace(/(,|\$)/g, "")) // Matches "," or "$" literally
    .toFixed(2)
    .toString()
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Comments