PHP method to retain 1 decimal place in division: 1. Use the "number_format()" function, the syntax is "number_format(dividend/divisor, 1)"; 2. Use the sprintf() function, the syntax is "sprintf ("%.1f", dividend/divisor)".
The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer
number_format() function formats numbers by thousands grouping.
Note: This function supports one, two or four parameters (not three).
Syntax
number_format(number,decimals,decimalpoint,separator)
Parameter Description
number Required. The number to format. If no other parameters are set, the number is formatted without a decimal point and with a comma (,) as the thousands separator.
decimals Optional. Specify the number of decimal places. If this parameter is set, numbers are formatted using a period (.) as the decimal point.
decimalpoint Optional. Specifies the string used as the decimal point.
separator Optional. Specifies the string used as thousands separator. Only the first character of the parameter is used. For example, "xxx" only outputs "x".
Note: If this parameter is set, all other parameters are required.
sprintf() function writes a formatted string into a variable.
arg1, arg2, parameters will be inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, insert arg1, at the second % sign, arg2, and so on.
Note: If there are more % symbols than arg arguments, you must use placeholders. The placeholder is inserted after the % symbol and consists of a number and "\$". See Example 2.
Syntax
sprintf(format,arg1,arg2,arg++)
Parameter Description
format Required. Specifies a string and how to format variables within it.
The example is as follows:
<?php $x=17; $y=7; $z=$x / $y; echo number_format($z, 1)."<br>"; echo sprintf( "%.1f ",$z); ?>
Output result:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to keep 1 decimal place in PHP division. For more information, please follow other related articles on the PHP Chinese website!