Home > Article > Backend Development > How to convert string to double type in php and retain two decimal places
Methods to convert and retain two decimal places: 1. Use the "floatval(string)" statement to convert the string to double type; 2. Use "number_format(double type value, 2)" or "sprintf" ("%.2f",double type value)" statement to retain two decimal places.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php converts string to double type And retain two decimal points
You can see two parts:
Convert the string to double type: use floatval()
Preserve two decimal points for double values: Use the number_format() or sprintf() function
number_format() can be used to format numbers by thousands grouping.
The sprintf() function writes a formatted string into a variable.
Sample code:
<?php header('content-type:text/html;charset=utf-8'); $double1=floatval("123"); echo "<br>使用number_format()保留两位小数:".number_format($double1, 2); echo "<br>使用sprintf()保留两位小数:".sprintf("%.2f",$double1); $double2=floatval("123.322"); echo "<br><br>使用number_format()保留两位小数:".number_format($double2, 2); echo "<br>使用sprintf()保留两位小数:".sprintf("%.2f",$double2); ?>
Instructions:
When using the number_format() or sprintf() function to retain two decimal places, if the missing value is greater than 5, it will be rounded.
<?php header('content-type:text/html;charset=utf-8'); $double=floatval("123.325"); echo "使用number_format()保留两位小数:".number_format($double, 2); echo "<br>使用sprintf()保留两位小数:".sprintf("%.2f",$double); ?>
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to convert string to double type in php and retain two decimal places. For more information, please follow other related articles on the PHP Chinese website!