Mark Anderson
YaBB Administrator
Offline
User - not staff!
Posts: 5689
Southsea, UK
|
Over the weekend, another approach occurred to me. This one is to set a String to the Number - which we're doing anyway - and then use a regex with .replace(). so: $MyString = $MyNumber.replace("(\d)(?=(\d{3})+[^\d])","$1,")12345.678 -> 12,345.678 In some locales, spaces are use instead of comma, in which case use "$1 " instead of "$1," as the replacement string: 12345.678 -> 12 345.678 Notes: - There is an implicit Number -> String coercion here as .replace() doesn't chain to Number-type data.
- Initially, I tried setting $MyString = $MyNum and only then applying .replace() to $MyString, but it seems OK to leave out that step.
- If you have decimal places but whose number of places vary (i.e. you can't be certain how many) don't be tempted to use Number.precision(N) as if N is omitted, zero is assumed, all decimal places are omitted rounding out to an integer output. IOW, Number.precision() for 4.95 is "5". Same applies for Number.format().
- Edge case [sic] with long number sequences. Although exponential formats are allowed with Number-type data for very large or small number, TB doesn't seem to honour explicit digit strings of over 9 characters. The latter seem to get round/truncated to 9 characters, so although a Number-derived String of over 9 characters can be created likely many will just be zeroes. Most likely this is because to date there hasn't been a need for playing with really long number strings!
[later] Digging further - having read this wikipedia page on numbering - let's assume we want space digit grouping and a comma as decimal separator: $MyString = $MyNum.replace("(\d)(?=(?:\d{3})+([^\d]))","$1 ","x").replace("\.",",")It uses 2 chained replacements, one for each delimiter: 1234567.89 --> 1 234 567,89One replace is needed for each character type you wish to replace. So: $MyString = $MyNum.replace("\.","'").replace("(\d)(?=(?:\d{3})+([^\d]))","$1.")1234567.89 --> 1.234.567'89Note in the latter the desired character changes mean the decimal point substitution needs to occur first.
|