Home > Back-end >  Rounding last decimal place to 0?
Rounding last decimal place to 0?

Time:01-05

I tried round, ceil and floor, but they do not seem to do what I want (or I dont see the wood for the trees :-))

This is what I want:

1.44 --> 1.40
1.23 --> 1.20
3.50 --> 4.00
2.48 --> 2.50
...

I did not find a way to achieve that. Should be possible?

Thanks!

CodePudding user response:

You can combine round() and number_format():

For example:

$number = 1.44;
number_format(round($number, 1), 2, '.', ''); // 1.40

CodePudding user response:

I'd use sptrintf to format the number to 1 decimal, then append a 0 behind it:

sprintf('%0.1f0', $test)

Test cases:

<?php

foreach ([ 1.44, 1.23, 3.50, 2.48 ] as $test) {
    $rounded = sprintf('%0.1f0', $test);
    var_dump($rounded);
}
string(4) "1.40"
string(4) "1.20"
string(4) "3.50"
string(4) "2.50"

Try it online!


As string, since trailing 0 on a float are removed by PHP

CodePudding user response:

I don't think there is a native php function already doing what you want. We will need to do it ourself. First by finding the depth of the decimal part, then by rounding depending on depth.

<?php

function roundToSecondLastDigit(float $number): float{
    $decimal = $number - intval($number);
    $depth = strlen((string) $decimal) - 2;
    
    return round($number, $depth - 1);
}

echo roundToSecondLastDigit(1.44) . "\n"; //1.4
echo roundToSecondLastDigit(1.23) . "\n"; //1.2
echo roundToSecondLastDigit(3.50) . "\n"; //4
echo roundToSecondLastDigit(2.48) . "\n"; //2.5

You can print your number with the precision you want with number_format then.

echo number_format(roundToSecondLastDigit(2.48), 2, '.', ''); //2.50
  • Related