Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove last digit from decimal number in PHP

Tags:

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.

like image 694
nikitz Avatar asked Dec 06 '25 02:12

nikitz


2 Answers

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>';
        }
    }
}
?>
like image 53
MonkeyZeus Avatar answered Dec 08 '25 16:12

MonkeyZeus


echo round(14.153, 2);  // 14.15

The round second parameter sets the number of digits.

like image 40
Clauss Avatar answered Dec 08 '25 16:12

Clauss