温馨提示×

PHP四舍五入在数组操作中的应用

PHP
小樊
81
2024-10-16 13:11:08
栏目: 编程语言

在 PHP 中,可以使用 array_map() 函数将四舍五入应用到一个数字数组中的每个元素

<?php
// 创建一个包含浮点数的数组
$numbers = [1.234, 2.678, 3.910, 4.567];

// 定义一个匿名函数,用于四舍五入输入的数字
$roundFunction = function ($number) {
    return round($number, 2);
};

// 使用 array_map() 函数将四舍五入应用到数组的每个元素
$roundedNumbers = array_map($roundFunction, $numbers);

// 输出四舍五入后的数组
print_r($roundedNumbers);
?>

上述代码会输出以下结果:

Array
(
    [0] => 1.23
    [1] => 2.68
    [2] => 3.91
    [3] => 4.57
)

在这个示例中,我们首先创建了一个包含浮点数的数组 $numbers。然后,我们定义了一个匿名函数 $roundFunction,该函数接受一个数字作为参数,并使用 PHP 的内置 round() 函数将其四舍五入到两位小数。最后,我们使用 array_map() 函数将 $roundFunction 应用到 $numbers 数组的每个元素,并将结果存储在 $roundedNumbers 数组中。

0