2018-10-07 18:42

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

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 3年前
• 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

点赞 评论 复制链接分享