duane2364 2016-02-01 20:33
浏览 50
已采纳

Php方程:变量减去相同的舍入变量,可能吗?

I need to echo number(variable) in two ways and i need help with code for this equation. Example:

Variable is 5003

First echo has to be: 5000 (rounded)

Second echo has to be just the rounded digits: 3

So i want to know if and how can i achieve this equation, im thinking among lines of: variable(5003) minus rounded variable(5000) equals 3

So that way if variable is lets say 15009

Fist will be 15000 Second will be 9

I hope this make sense, thank you for help

  • 写回答

2条回答 默认 最新

  • douzhou7124 2016-02-01 20:36
    关注

    You should look into the roundPHP function:

    You can have negative decimal points like this:

    round(5003, -3);  // returns 5000
    round(15009, -3); // returns 15000
    

    To figure out the difference you can do like this:

    $input = 5003
    $x = $input;
    $y = round($input, -3);
    $z = $x - $y; // z is now 3
    

    PHP is not a mathematical language, so it cannot solve equations for you.

    You can make a more general solution like this:

    $inputs = [
        5003,
        15009,
        55108,
        102010
    ];
    
    foreach ($inputs as $input) {
        $decimals = floor(log10($input)) - 1;
        $rounded = round($input, -1 * $decimals);
        echo "$input - $rounded = " . ($input - $rounded) . PHP_EOL;
    }
    

    Outputs:

    5003 - 5000 = 3
    15009 - 15000 = 9
    55108 - 55000 = 108
    102010 - 100000 = 2010
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部