PHP decimal rounding example tutorial

零下一度
Release: 2023-03-10 18:32:01
Original
1371 people have browsed it

Content of this section:
How to round decimals in php and js

The first part:

1, discard the decimal part and keep the integer part

Copy codeCode example:

php: intval(7/2)
js:parseInt(7/2)
Copy after login

2, round up, if there is a decimal, add 1 to the integer part

Copy codeCode example:

php: ceil(7/2)
js: Math.ceil(7/2)
Copy after login

3, round down.

Copy codeCode example:

php: round(7/2)
js: Math.round(7/2)
Copy after login

4, round down

Copy codeCode example:

php: floor(7/2)
js: Math.floor(7/2)
Copy after login

Part 2, PHP roundingCommonly used functions
In phpProgramming, the commonly used rounding functions are ceil, floor, round, intval .

Let’s introduce them separately.

1, ceil -- rounding method

Introduction
float ceil (float value)

Return not less than =noted id =note_temp>value is the next integer. If value has a decimal part, it will be carried. The return type of ceil() is still float. The float value range is usually larger than eger.

Example 1. ceil

Copy code code example:

<?php
echo ceil(4.3);     // 5
echo ceil(9.999);     // 10
?>
Copy after login

2, floor -- rounding by rounding off method

Introduction

float floor ( float value )
Copy after login

Return the next integer not greater than value will be value as a decimal Partial rounding and rounding floor return type is still float float value range is usually larger than eger

Example 1. floor

Copy code code example:

<?php
echo floor(4.3);     // 4
echo floor(9.999); // 9
?>
Copy after login

3, round -- round floating point numbers by 4 and 5

Introduction

float round (float val [, precision])

Return val according to Specify precision (the number of digits after the decimal point) to round the result precision. It can also be a negative number or zero (default value)

Example 1. round

Copy code code example :

<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6);// 4
echo round(3.6, 0);// 4 
// www.jbxue.com
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
Copy after login

4, val---convert the variable into an integer type
Example 1, val

Copy code code example:

<?phpecho val(4.3);    //4echo val(4.6); // 4  
?>
Copy after login

The above is the detailed content of PHP decimal rounding example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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