Home >Backend Development >PHP Problem >How to remove the content after the decimal point in php

How to remove the content after the decimal point in php

PHPz
PHPzOriginal
2023-03-23 17:21:072227browse

In PHP, the processing of floating point numbers has always been a headache. This is because the representation of floating point numbers in computers is limited, and many calculations of floating point numbers will produce errors. Among them, in the output, we often want to keep only the few decimal places and remove the unnecessary parts. This article introduces several methods of removing decimals in PHP.

1: Use the number_format function

number_format() function can format numbers into a common thousands separator format. It also controls the number of digits displayed after the decimal point. We can achieve the effect of retaining decimals and removing decimals by passing two parameters in the number_format function. The first parameter is the number to be formatted, and the second parameter is the number of decimal places to retain.

<?php
// 保留两位小数
$num = 3.1415926;
echo number_format($num, 2); // 3.14
// 去掉小数
$num = 3.1415926;
echo number_format($num, 0); // 3
?>

Two: Use the round function

Use the round function to round floating point numbers to the specified precision and return the result. The first parameter is the number to be rounded, and the second parameter is the number of decimal places to be retained.

<?php
// 保留两位小数
$num = 3.1415926;
echo round($num, 2); // 3.14
// 去掉小数
$num = 3.1415926;
echo round($num, 0); // 3
?>

Three: Use the intval function

intval can convert a string or floating point number into an integer while removing the decimal part. It should be noted that intval automatically performs rounding down when converting floating point numbers.

<?php
$num = 3.1415926;
echo intval($num); // 3
?>

Four: Use the floor function

The floor function can round a floating point number down to the nearest integer value. It is also important to note that floor will automatically perform rounding down when converting floating point numbers.

<?php
$num = 3.7;
echo floor($num); // 3
?>

In actual development, we often need to decide how many decimal places to retain or whether to remove decimals based on business needs. Through the methods introduced above, you can easily retain and remove decimals, thereby bringing more convenience to your project.

The above is the detailed content of How to remove the content after the decimal point 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