Page 1 of 1

Native way to round a number to x decimals?

Posted: Sun Jul 11, 2021 5:41 pm
by philipbergwerf
Is there a native/built-in way to round a number to x decimals in pixilang?

I was searching for something like:

Code: Select all

fn round($x, $decimal)
{
	ret([rounded $x on $decimal decimals])
}

Re: Native way to round a number to x decimals?

Posted: Sun Jul 11, 2021 7:28 pm
by philipbergwerf
I found this solution:

Code: Select all

// Round $x to $d decimals.
fn round($x, $d)
{
    fn integer($x)
    {
        $base = floor($x)
        $dec = $x - $base
        if $dec >= 0.5 {ret($base + 1)}
        else {ret($base)}
    }
    $base = floor($x)
    $dec = integer(($x - $base) * pow(10, $d)) / pow(10, $d)
    ret($base + $dec)
}
But still is there a better shorter way? This solution works :)