I have a value in database which contains 20 numbers, example : 1.1234567891011223
I want to limit the echoed value to 1.123 or 1.12 only instead of this long number..
How can I do that in PHP?
I have a value in database which contains 20 numbers, example : 1.1234567891011223
I want to limit the echoed value to 1.123 or 1.12 only instead of this long number..
How can I do that in PHP?
It sounds like you're looking for either the round
function:
$long_number = 1.1234567891011223;
$formatted_number = round($long_number, 2);
echo $formatted_number; // 1.12
Or the number_format
function:
$long_number = 1.1234567891011223;
$formatted_number = number_format($long_number, 2, '.', '');
echo $formatted_number; // 1.12
Hope this helps! :)
is this what you are searching for? http://php.net/manual/de/function.number-format.php
use it like that:
<?php
$a = 1.1234567891011223;
echo number_format ( $a , 3 , '.', '');
?>
Take a look at strpos and substr. Below is an example from another post @Nineoclick This function finds the decimal and rounds the number. Rounding the number will shorten it.
truncate(1.1234567891011223, 2)
function truncate($val,$p = 0)
{
$strpos = strpos($val, '.');
return $p < 0 ? round($val,$p) : ($strpos ? (float)substr($val,0,$strpos+1+$p) : $val);
}
You can also use sprintf for this
$formatted = sprintf("%01.2f", $longNum);
Or if you're just going to echo it and don't need the variable, printf
printf("%01.2f", $longNum);