2

I'm new to knockout and just starting to get my head around the framework. However, I've come into a problem whereby I'm trying to format large numbers with commas. I've been able to get the number to format to decimal places using the extenders API but this isn't what I want.

The number is stored in an array and an example of a number used in the app will be 5 million. So I need the values to print out 5,000,000 - is this possible? I'm guessing it has to be.

leaksterrr
  • 3,800
  • 7
  • 34
  • 65
  • So basically you're looking for a javascript function to convert 5000000 into 5,000,000? – GôTô Apr 16 '14 at 09:05
  • Yes but it has to be compatible with knockout and binds to the data it's formatting so it updates in real-time & keeps the comma separated structure. – leaksterrr Apr 16 '14 at 09:32
  • How do you interact with the data? Do you change the value in some place and need a text field to update with the converted value? Or is it in the same place (an input text tag)? – GôTô Apr 16 '14 at 09:35
  • this might help: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Tanner Apr 16 '14 at 09:50
  • Yeah, the value gets changed elsewhere and the text that gets output needs to update with the converted value + comma separated structure. – leaksterrr Apr 16 '14 at 10:15
  • possible duplicate of [create an computed observable for formatted values for a bunch of variables](http://stackoverflow.com/questions/13996635/create-an-computed-observable-for-formatted-values-for-a-bunch-of-variables) – Jeremy J Starcher Apr 16 '14 at 10:40
  • No because if you read it carefully, you'd see that it just adds decimal places with no comma-separation. – leaksterrr Apr 16 '14 at 11:05

2 Answers2

4

For the formatting, you can use the following regex (warning: it does not work with float): mystring.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

You can check out this example: http://jsfiddle.net/nyothecat/XgezN/1/

GôTô
  • 7,974
  • 3
  • 32
  • 43
0

I think you'll want to create a custom binding. The easiest thing would probably be to use an existing jQuery formatter to format the display when the observable changes and then set up an event handler for the textbox to parse the textbox (removing the commas) when the users types something new.

Community
  • 1
  • 1
PatrickSteele
  • 14,489
  • 2
  • 51
  • 54