Home  >  Article  >  Backend Development  >  What are the methods for rounding decimals in PHP?

What are the methods for rounding decimals in PHP?

青灯夜游
青灯夜游Original
2021-09-22 19:24:243496browse

Method: 1. Use intval() function, syntax "intval($num)"; 2. Use ceil() function, syntax "ceil($num)"; 3. Use floor() function, The syntax is "floor($num)"; 4. Use the round() function, the syntax is "round($num)".

What are the methods for rounding decimals in PHP?

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

php decimal rounding Method

#1. Use the intval() function

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = intval($num);
echo &#39;变量 $int 的类型为:&#39;.gettype($int).&#39;<br>&#39;;
var_dump($int);
?>

What are the methods for rounding decimals in PHP?

intval() function is used to obtain The integer value of the variable; this function is often used for data type conversion to convert string and floating-point type variables into integer types.

2. Use the ceil() function - round up, if there is a decimal, add 1 to the integer part

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = ceil($num);
echo &#39;变量 $int 的类型为:&#39;.gettype($int).&#39;<br>&#39;;
var_dump($int);
?>

What are the methods for rounding decimals in PHP?

3. Use the floor() function--round down

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = floor($num);
echo &#39;变量 $int 的类型为:&#39;.gettype($int).&#39;<br>&#39;;
var_dump($int);
?>

What are the methods for rounding decimals in PHP?

4. Use the round() function--round up

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 123.456;
$int = round($num);
echo &#39;小数值为:&#39;.$num.&#39;<br>&#39;;
echo &#39;取整后值为:&#39;.$int .&#39;<br>&#39;;
var_dump($int);

$num = 123.556;
$int = round($num);
echo &#39;小数值为:&#39;.$num.&#39;<br>&#39;;
echo &#39;取整后值为:&#39;.$int .&#39;<br>&#39;;
var_dump($int);
?>

What are the methods for rounding decimals in PHP?

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What are the methods for rounding decimals in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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