Current Location: Home> Latest Articles> Use strval to convert floating numbers and retain the specified number of decimal places

Use strval to convert floating numbers and retain the specified number of decimal places

gitbox 2025-05-26

1. Use strval() to convert directly

The basic usage of strval() is to directly convert floating point numbers into strings, but it retains all significant numbers of floating point numbers and cannot limit the number of decimal places.

 <?php
$num = 3.1415926;
echo strval($num); // Output "3.1415926"
?>

Although simple, it has no control over how many decimal places are retained.


2. Use number_format() to format first, and then convert with strval()

number_format() is a built-in PHP function that is specially used to format numbers and can specify the number of decimal places.

 <?php
$num = 3.1415926;
$formatted = number_format($num, 2);  // reserve2Decimal number,The result is a string
echo strval($formatted);  // Output "3.14"
?>

number_format() itself returns a string. The wrapping of strval() here is to meet the requirements of the question, but it is actually not necessary.


3. Combine sprintf() formatting and then convert with strval()

sprintf() is also a common method for formatting strings, and can flexibly specify the number of reserved decimal places.

 <?php
$num = 3.1415926;
$formatted = sprintf("%.3f", $num); // reserve3Decimal number,Return string
echo strval($formatted); // Output "3.142"
?>

Similarly, sprintf() returns a string, and using strval() is just an unnecessary wrapper.


4. Customize the function, first round() , and then convert it to a string

Sometimes, we want to use the round() function to process the decimal point first, and then convert it into a string.

 <?php
function floatToString($num, $decimals) {
    $rounded = round($num, $decimals);
    return strval($rounded);
}

echo floatToString(3.1415926, 2); // Output "3.14"
echo "\n";
echo floatToString(3.1000, 2);   // Output "3.1",Note that no zero is added
?>

Here, round() ensures the accuracy of the numerical value, but does not automatically fill the zeros in the decimal places.


5. A combination method that retains the number of decimal places and automatically fills the zeros

If you need to keep a fixed decimal place and automatically make up for zeros, you can use number_format() as the simplest way:

 <?php
$num = 3.1;
echo strval(number_format($num, 3));  // Output "3.100"
?>

Summarize

  • Straval() direct conversion cannot control the number of decimal places.

  • It is recommended to format the numbers with number_format() or sprintf() first to get a string with a specified decimal number, and then wrap it with strval() (actually, it's OK not to wrap it).

  • round() can be used for rounding, but does not automatically make up for zeros.

  • The final method is determined based on whether the zero-complement is required and the format requirements.