How can PHP be used to enforce specific decimal precision in user input for prices?

When dealing with user input for prices, it is important to enforce specific decimal precision to ensure consistency and accuracy. One way to achieve this in PHP is by using the number_format() function to format the input to the desired precision. This function allows you to specify the number of decimal places you want to display, rounding the input if necessary.

// Get user input for price
$userInput = $_POST['price'];

// Enforce 2 decimal places precision
$price = number_format((float)$userInput, 2, '.', '');

// Output the formatted price
echo 'Formatted Price: $' . $price;