Home > Backend Development > PHP Problem > How to convert string to double type in php and retain two decimal places

How to convert string to double type in php and retain two decimal places

青灯夜游
Release: 2023-03-15 19:04:01
Original
3673 people have browsed it

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.

How to convert string to double type in php and 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(&#39;content-type:text/html;charset=utf-8&#39;);   
$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);
?>
Copy after login

How to convert string to double type in php and retain two decimal places

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$double=floatval("123.325");
echo "使用number_format()保留两位小数:".number_format($double, 2);
echo "<br>使用sprintf()保留两位小数:".sprintf("%.2f",$double);
?>
Copy after login

How to convert string to double type in php and retain two decimal places

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!

Related labels:
php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template