Home > Backend Development > PHP Tutorial > How to Round a PHP String to Two Decimal Places?

How to Round a PHP String to Two Decimal Places?

Susan Sarandon
Release: 2024-12-28 01:19:09
Original
896 people have browsed it

How to Round a PHP String to Two Decimal Places?

Rounding a Number to Two Decimal Places in PHP

In this snippet, we aim to round a PHP string to two decimal places to format it properly for output. To achieve this, we could utilize a custom function named round_to_2dp().

The function definition should be as follows, employing the number_format() function:

function round_to_2dp($number) {
    return number_format((float)$number, 2, '.', '');
}
Copy after login

Here's an example of its usage:

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number; // Outputs 520.00
Copy after login

The number_format() function takes three arguments:

  1. Number: The value to be formatted.
  2. Decimals: The number of decimal places to round to.
  3. Decimals Separator: The character used to separate decimal digits.
  4. Thousands Separator: The character used to separate thousands.

In this case, we set the decimals argument to 2, specifying two decimal places. The final result is returned as a string.

The above is the detailed content of How to Round a PHP String to Two Decimal Places?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template