Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

print 1,000 instead of 1000?

What should I do, if I have a variable which has a numeric value of 1000, and I want to print it as "1,000" instead of "1000"?

By the way, I am new to Twine and to coding. So if anything I said doesn't make sense, please let me know. Thanks!

Comments

  • To do what you want you need to convert your number to a formatted string (text), unfortunately javascript does not have this feature by default so you need to add it.

    1. Creating a Script passage and adding the following code to it:

    /**
    * Number.prototype.format(n, x)
    *
    * @param integer n: length of decimal
    * @param integer x: length of sections
    */
    Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
    };
    2. Test the new format feature by adding the following to your Start passage:

    Formating Numbers (no decimal point):
    1234 => <<set $a to 1234>><<print $a.format()>>
    12345 => <<set $a to 12345>><<print $a.format()>>
    123456 => <<set $a to 123456>><<print $a.format()>>
    1234567 => <<set $a to 1234567>><<print $a.format()>>
    12345678 => <<set $a to 12345689>><<print $a.format()>>


    Formating Numbers (with 2 decimal points and roumding):
    1234 => <<set $a to 1234>><<print $a.format(2)>>
    1234.5 => <<set $a to 1234.5>><<print $a.format(2)>>
    1234.56 => <<set $a to 1234.56>><<print $a.format(2)>>
    1234.567 => <<set $a to 1234.567>><<print $a.format(2)>>

    Formating Numbers (with different decimal points and comma placements):
    123456.7 => <<set $a to 123456.7>><<print $a.format(3,2)>>
    123456.789 => <<set $a to 123456.789>><<print $a.format(2,4)>>
    Hope that helps
  • greyelf, thank you so much!! It works perfectly  ;D
Sign In or Register to comment.