简体   繁体   中英

How can I remove last digit from decimal number in PHP

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.

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>';
        }
    }
}
?>
echo round(14.153, 2);  // 14.15

第二个舍入参数设置位数。

You can try this.

Live DEMO

<?php

  $number = 14.153;

  echo number_format($number,2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM