舍入或小数后修剪

时间:2016-08-27 23:44:53

标签: php function

如果我的$number等于4853.14248325523

function formatMoney($number) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } 
    return '$'.$number;
} 

我的函数formatMoney()将返回值$4,853.142483,25523

但是,我希望函数返回$4,853.14

的值

2 个答案:

答案 0 :(得分:6)

不需要使用正则表达式自己滚动,php内置函数来处理这个:

$number=4853.14248325523;

echo '$'.number_format($number,2, '.', ',');

返回$4,853.14

手册页number_format()

答案 1 :(得分:2)

PHP有一个非常好的money_format函数:

// 2. FOR "NEW CREATED" AND PUBLISHED PRODUCT
add_action('transition_post_status', 'product_custom_fields_action', 10, 3);
function product_custom_fields_action($new_status, $old_status, $post) {
    $post_id = $post->ID;
    if( $old_status != 'publish' && $new_status == 'publish' && !empty($post_id) && in_array( $post->post_type, array( 'product') ) )
        custom_fields_creation( $post->ID );
}