-3

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!

CerebralFart
  • 3,336
  • 5
  • 26
  • 29
  • 5
    Have you tried just using string concatenation? `this.value = "$" + parseFloat(... the rest)` – hotforfeature Jun 09 '16 at 17:38
  • 1
    @hotforfeature. best possible answer. sometimes people just can't see the forest for the trees... – Marc B Jun 09 '16 at 17:40
  • @hotforfeature That works but when you try to change the amount again it returns $NaN (Thankyou) – Andrés Montero Jun 09 '16 at 17:43
  • 1
    Based on the comments above you can try remove the dollar sign from the string before doing some calculations and when you are done just add it back. – Cengiz Araz Jun 09 '16 at 17:45
  • `toFixed()` returns a String, you can safely remove the subsequent call to `toString()`. Incidentally I'd suggest displaying the currency using either CSS generated content, or simply inserting an element prior to the element holding the ``. – David Thomas Jun 09 '16 at 17:46

4 Answers4

2

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, ",");
}
hotforfeature
  • 2,558
  • 1
  • 16
  • 24
0

Checkout my answer for a previous question similar to this:

Adding Two Decimal Places using JavaScript

Community
  • 1
  • 1
Oshadha
  • 546
  • 10
  • 25
0

accounting.js is a tiny JavaScript library for number, money and currency formatting.

http://openexchangerates.github.io/accounting.js/

Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
0

Created codepen url for reference.. I just tried add that onblur function on the input field

var x = (document.getElementById("numbers").value);
x = "$"+((x)*1).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");

http://codepen.io/nagasai/pen/LZGWjp

David Thomas
  • 249,100
  • 51
  • 377
  • 410
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40