我有一个包含多个带数字索引值的数组。每个值的数据类型是字符串。它应该是一个浮点数(38.50,22.12等)。 我现在要做的是从数组中减去每个我想要指定的数字值。然后,找到绝对数字,以防减法给出负数作为结果。
我该怎么做?
答案 0 :(得分:3)
您想要查看array_map()函数。
答案 1 :(得分:2)
我不知道这是不是你的意思:
$original_array = array('38.50', '22.12');
function sort( $n ){
$num = 12.0;
return (double)$n - $num;
}
$newarray = array_map("sort", $original_array );
将整数或字符串转换为float可能会很痛苦。
使用这些函数中的任何一个都会首先将它们转换为适当的浮点数:
function float_format( $number, $decimal = 2, $decimal_sep = '.', $thousands_sep = '' ){
return number_format($number, $decimal, $decimal_sep, $thousands_sep);
}
function float_val( $number, $decimal, $float_locale = 'f' ){
//f - the argument is treated as a float, and presented as a floating-point number (locale aware).
//F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
return (double)sprintf("%.".$decimal.$float_locale, $number);
}
第一个更适合货币。希望这会有所帮助。