duanlie1298 2018-10-07 18:42
浏览 29
已采纳

在PHP中的十进制数字中的某个点之后有没有办法正则表达式和删除? [重复]

This question already has an answer here:

Is there any way to do a regex that cuts off a number at a certain point without rounding (simply drops the digits?) say after 4 digits.... It will not be handling negative numbers, EVER. I could have number inputs such as 0.03123 or 1.31, or 10000.98, etc .... What I have written so far as my solution is rounding and not what I'm seeking....

$number = 10000.51999999;
$precision = 4;
echo "<br>";

// grab number before decimal by rounding down the whole number down...
$numberBeforeDecimal = floor($number); 
echo "<br>";

// grab the decimal and set the correct precision needed
$n = $number;
intval($n); // 12
$theDecimalPart = explode('.', number_format($n, ($precision)))[1]; // 3430

echo $theDecimalPart; // this is outputting 5200

$theNewValue = $numberBeforeDecimal.".".$theDecimalPart;
</div>
  • 写回答

1条回答 默认 最新

  • dongmo6937 2018-10-07 18:50
    关注
    • explode() the number to get integer and decimal part separated out in an array
    • Use substr() function to get relevant precision from the decimal part.
    • Finally, concatenate them back.

    Try the following (Rextester DEMO):

    $number = 10000.51999999;
    $precision = 4;
    
    // separate out the integer and decimal part
    $number_str_arr = explode('.', $number);
    
    // concatenate them back
    $theNewValue = $number_str_arr[0] . '.' . substr($number_str_arr[1], 0, $precision);
    echo $theNewValue; // displays 10000.5199
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器