Native way to round a number to x decimals?

Pixilang programming language
Post Reply
philipbergwerf
Posts: 136
Joined: Sat Mar 17, 2018 4:23 pm

Native way to round a number to x decimals?

Post 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])
}
philipbergwerf
Posts: 136
Joined: Sat Mar 17, 2018 4:23 pm

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

Post 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 :)
Post Reply