Howdy, Stranger!

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

Formatting a float in Harlowe

I use Twine 2.0 with Harlowe 1.2.4.
Is there a posibility to format a float? I know that working with floats can be a little tricky (e.g. 3.9999999 instead of 4).
I have a variable and its initial value is 100 and I want to substract from that number a different values e.g. 100 - 0.2, but (to avoid this "3.99999" in decimals) now I want to format a result decimal to 2 decimal places (99.80, eventually 99.78). Is it possible to format a decimal to a particular number of decimal places? Maybe the only option is to use javascript.


  • edited May 2017
    A cheap and dirty way to do it without JavaScript would be to multiply and then divide the number as a part of the rounding operation.
    (set: $var to 2)
    (set: $var to it + 0.286)
    (set: $var to it * 100)
    (set: $var to (round: $var))
    (set: $var to it / 100)

    Fair warning though, floats are weird in JavaScript. So there may be some imprecision in your results.

    Edit. I forgot to mention I'm on my phone, so I didn't test this.
  • edited May 2017
    note: Because floating point maths can result in inconsistent values it is generally not a good idea to do it unless it is absolutely necessary. One comment technique used to get around this issue it to use integers instead and then to reformat the output as needed.

    In your case because you want two decimal places you would scale the initial values by two places (eg. multiple them by 100) then at the point you want to display the results you would reverse that scaling (divide it by 100) to get a temporary decimal which you would than use Javascripts toFixed() function on to format it as required.

    If you wanted a single decimal place you would multiple/divide by 10, and if you wanted three decimal places you would multiple/divide by 1000, etc...

    eg. The following is the integer equivalent of your example.
    (set: $var to 10000 - 20)
    var: (print: ($var / 100).toFixed(2))
  • I forgot to mention - it's not necessary for me to have a float. It can be integer, but in the result I want to have it look like a float.
    @greyelf: Thanks a lot! This
    (print: ($var / 100).toFixed(2))
    work for me perfectly :smile:
Sign In or Register to comment.