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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用