Page 1 of 1

[Solved] Format numbers with with two trailing digits?

Posted: 04 Jul 2025 20:11
by highend
Is there a pattern for format() that display a number always! with two trailing digits?

Examples:

Code: Select all

510 => 510.00
510.5 => 510.50
510.70 => 510.70
510.428 => 510.42 (no rounding wanted)
15386 => 15386.00

Re: Format numbers with with two trailing digits?

Posted: 05 Jul 2025 15:12
by admin
This should do:

Code: Select all

$n = 510.428; echo format(floor($n  * 100) / 100, "0.00");

Re: Format numbers with with two trailing digits?

Posted: 05 Jul 2025 15:32
by highend
Thanks, works as expected!

A more generalised function can now look like this:

Code: Select all

function getDecimal($num, $cntDigits=2) {
    $factor = 10 ^ $cntDigits;
    return format(floor($num * $factor) / $factor, "0." . strrepeat("0", $cntDigits));
}

Re: Format numbers with with two trailing digits?

Posted: 05 Jul 2025 15:37
by admin
Instead of 100 it should be 10 ^ $cntDigits.

Re: Format numbers with with two trailing digits?

Posted: 05 Jul 2025 16:48
by highend
Yeah, you're right, changed it in my previous post^^