-2

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?

junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33

5 Answers5

1

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! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

use round function

echo round(1.1234567891011223,2); // output: 1.12
aidinMC
  • 1,415
  • 3
  • 18
  • 35
0

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 , '.', '');
?>
Swittmann
  • 71
  • 1
  • 12
0

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);
}
Trevor V
  • 1,958
  • 13
  • 33
0

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);
Rob Ruchte
  • 3,569
  • 1
  • 16
  • 18