开发者

Substracting float from array

I have an array that contains multiple values with numerical index. The data type for each value is string. It was supposed to be a float number though (38.50, 22.12, etc). What I want to do now is subtract each values from the array with a number that I'd like to specify myself. And then, find the absolute num开发者_如何转开发ber in case the subtraction gives a negative number as the result.

How can I do that?


You want to look into the array_map() function.


I don't know if this is what you meant:

$original_array = array('38.50', '22.12');

function sort( $n ){
    $num = 12.0;
    return (double)$n - $num;
}

$newarray = array_map("sort", $original_array );

Converting an integer or a string to a float can be a pain though.

Using any of these functions will convert them to a proper float first:

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);
}

The first of which is better for currency. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜