1

I have helper function formatting my money value into pounds and pence:

formatMoney: function(10496.470000000001){
    return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "1,");
},

Gives me:

11,496.471,001,001,001

Is there a way I can format this accurately into pounds and pence? so it reads, £11,496.471p

Bomber
  • 10,195
  • 24
  • 90
  • 167

2 Answers2

0

In addition to the toFixed method call mentioned previously, the second parameter to replace should be "$1," rather than "1,". Also, your conversion to a number is somewhat fragile. Here's my attempt at remedying these issues:

function convert(value){
    return "£"+((Number(value)||0).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"))+"p";
}

console.log(convert(10496.470000000001));
Paul Humphreys
  • 338
  • 2
  • 9
-1

The Regexp doesn't care about the decimals you pass in. You need to convert your input to already have 2 decimals:

return value.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "1,");
             ^^^^^^^^^^

function convert(value){
    return value.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "1,");
}

console.log(convert(10496.470000000001));
putvande
  • 15,068
  • 3
  • 34
  • 50
  • Why does `10496.470000000001` format to `11,496.47`? PS. I didn't downvote. – Fred Jun 07 '16 at 12:43
  • Thats what you wanted right? Or does it need the extra `1`? – putvande Jun 07 '16 at 12:50
  • I am not the OP but I suspect the OP has an error in their script too. Unless I missed something and they do want to add a thousand as well as format to currency display. – Fred Jun 07 '16 at 12:52