Rounding problem

It has to do in part with JavaScript’s float point number and in part with processor limitation.

ChoiceScript relays all its arithmetic operations to the underlying JavaScript engine and uses the same primitives. ChoiceScript doesn’t have an integer type, only a number type.

I don’t know how much you’re interested into technical jargon, but here are two articles explaining what’s going on:

JavaScript Corner: Math and the Pitfalls of Floating Point Numbers

What Every JavaScript Developer Should Know About Floating Points


I whipped up this solution. This will round 0.5 or greater to 1, otherwise, return only the integer part (round down). You’ll need a return variable to capture the result.

*comment __startup.txt__
*create return 0

*commnet __utils.txt__
*label round
*params number
*temp floatPoint (number modulo 1)
*temp integerPart (number - floatPoint)
*if (floatPoint >= 0.5)
	*set integerPart  +1
*set return integerPart
*return

Then call it as usual:

*gosub_scene utils round 57.14
${return}

It should print 57.


@CJW, maybe we could add this to the cslib math module or number module. :thinking:

3 Likes