drw85135 2016-02-26 14:34
浏览 42
已采纳

四舍五入到一位小数

I am using a function to make 1000 to 1k and 1000000 to 1m but i want to add one decimal to it, i have gotten this far but it rounds up instead of down so if i enter 1565 i want to get 1.5 and only if i pass 1600 i want to get 1.6 (force round down) i use this function:

public function convert($Input){
    if($Input<1000){
        $AmountCode = "";
        $Amount = $Input;
    }
    else if($Input>=1000000){
        $AmountCode = "M";
        $Amount = round(floatval($Input / 1000000), 1, PHP_ROUND_HALF_DOWN);
    }
    else if($Input>=1000){
        $AmountCode = "K";
        $Amount = round($Input / 1000, 1, PHP_ROUND_HALF_DOWN);

    }

    $Array = array(
        'Amount' => $Amount,
        'Code' => $AmountCode
    );

    return $Array;

}

Scenario 1: what happens now if i enter 1565 i get 1.6 and if i enter 1545 i get 1.5 does any one know how to get the forcibly round it down?

Scenario 2: the number i enter is 10665 will be outputted as 10.7k (rounded up), but i want to to show as 10.6k (rounded down) which for somereason i can't figure out how to do that

  • 写回答

1条回答 默认 最新

  • dongxin991209 2016-02-26 15:45
    关注

    For rounding down in PHP, they have a function called floor(). Unfortunatly, this function does only return an int. However you can make it round down by multiplication first, and then division. See this post: PHP How do I round down to two decimal places?.

    This means your code would be something like this:

    else if($Input>=1000000){
        $AmountCode = "M";
        $Amount = floor(floatval($Input / 100000))/10;
    }
    else if($Input>=1000){
        $AmountCode = "K";
        $Amount = floor(floatval($Input / 100))/10;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路