[Solved] Format numbers with with two trailing digits?

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
highend
Posts: 14571
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

[Solved] Format numbers with with two trailing digits?

Post 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
One of my scripts helped you out? Please donate via Paypal

admin
Site Admin
Posts: 64917
Joined: 22 May 2004 16:48
Location: Win8.1, Win10, Win11, all @100%
Contact:

Re: Format numbers with with two trailing digits?

Post by admin »

This should do:

Code: Select all

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

highend
Posts: 14571
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: Format numbers with with two trailing digits?

Post 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));
}
One of my scripts helped you out? Please donate via Paypal

admin
Site Admin
Posts: 64917
Joined: 22 May 2004 16:48
Location: Win8.1, Win10, Win11, all @100%
Contact:

Re: Format numbers with with two trailing digits?

Post by admin »

Instead of 100 it should be 10 ^ $cntDigits.

highend
Posts: 14571
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: Format numbers with with two trailing digits?

Post by highend »

Yeah, you're right, changed it in my previous post^^
One of my scripts helped you out? Please donate via Paypal

Post Reply