Home > Backend Development > PHP Problem > How to keep 1 decimal place in PHP division

How to keep 1 decimal place in PHP division

WBOY
Release: 2023-03-15 10:22:01
Original
4618 people have browsed it

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)".

How to keep 1 decimal place in PHP division

The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer

How to keep 1 decimal place in PHP division

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)
Copy after login

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++)
Copy after login

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);
?>
Copy after login

Output result:

How to keep 1 decimal place in PHP division

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!

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