0 votes
by (310 points)
I found the (round:) macro, but it rounds 0.5 up, and for what I'm doing (D&D ability score modifiers), I need to round down at the half instead of up.  Can this be done without writing a big if/else statement?

2 Answers

+1 vote
by (2.7k points)

Hi, sirjohnthetall,

following snippet works for me, and is not sooo big, I would argue:

(if: ($inpFloat - (floor: $inpFloat)) is 0.5)[\
        (set: $res to (floor: $inpFloat))]
(else:)[(set: $res to (round: $inpFloat))]

Then I played a bit around with different numbers:

passage named 'Start':
 

{ <!-- this (until the closing brace) only to avoid lines of empty space in output -->
<!-- prompt for input -->

(set: $inpFloat to (num: (prompt: "Enter number, point delimiter", "1.5")))


<!-- calc the result, should x.5 round down to x -->

(if: ($inpFloat - (floor: $inpFloat)) is 0.5)[(set: $res to (floor: $inpFloat))]
(else:)[(set: $res to (round: $inpFloat))]

}
<!-- show result to user and provide restart link for more -->

inpFloat:>|$inpFloat|< rounded to >|$res|<

[[Again?->Start]]

There is a kind of funny effect, I think which is founded in Javascript, not in Twine2/Harlowe2.

0.500000000000000      => 0
0.500000000000001      => 1   
0.5000000000000001    => 1
0.50000000000000001  => 0

 

0 votes
by (159k points)

Because the rounding method being used rounds all x.5 decimal numbers up to the next higher integer, including negative decimal number, a common trick used to achieve the result you want is to first convert the original number into a negative and then reversing that process with the integer result.

(set: $decimal to 1.5)\
(set: $integer to -(round: -$decimal))\

decimal: $decimal
rounded integer: $integer

... notice the negative signs before the $decimal variable and the (round:) macro.

...