How can I remove last digit from decimal number in

2020-04-21 05:14发布

I want to remove last digit from decimal number in PHP. Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.

标签: php
3条回答
够拽才男人
2楼-- · 2020-04-21 05:34

I think this should work:

<?php
$num = 14.153;
$strnum = (string)$num;

$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;

$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3

if($decimalPoints > 0)
{
    for($i=0 ; $i<=$decimalPoints ; $i++)
    {
        // substring($strnum, 0, 0); causes an empty result so we want to avoid it
        if($i > 0)
        {
            echo substr($strnum, 0, '-'.$i).'<br>';
        }
        else
        {
            echo $strnum.'<br>';
        }
    }
}
?>
查看更多
贪生不怕死
3楼-- · 2020-04-21 05:39
echo round(14.153, 2);  // 14.15

The round second parameter sets the number of digits.

查看更多
Lonely孤独者°
4楼-- · 2020-04-21 05:39

You can try this.

Live DEMO

<?php

  $number = 14.153;

  echo number_format($number,2);
查看更多
登录 后发表回答