Good afternoon, guys, tell me the implementation of the function of smart decimal numbers, a simple implementation of rounding is not suitable as the numbers can be ten-digit but may not be

the task is such that there are calculations and maybe a figure

1) 0,00025325 2) 0,0000000225 3) 0.02501 

and I need to show in each number two characters after zeros, for example:

 0,00025 0,000000022 0.025 

How can you implement something like this in one function?

As I see the solution, but mine function is complicated and I would like easier

  public static function numbersAfterDecimalPoint($number) { $number = number_format($number, 10, ',', ' '); $breakUpNumber = explode(",", $number); if(!isset($breakUpNumber[1])){ return $number; } $lang = iconv_strlen($breakUpNumber[1]); $number = ''; $counter = 0; for ($i = 0; $i < $lang; $i++){ if($breakUpNumber[1][$i] == '0'){ $number .= $breakUpNumber[1][$i]; }else{ $number .= $breakUpNumber[1][$i]; $counter++; if($counter == 2){ break; } } } if($counter == 0){ return number_format($number, 2, ',', ' '); } return $breakUpNumber[0].','.$number; } 
  • What have you tried to do? - Jean-Claude
  • Yes, he attached his decision - Eugene Kolesnik
  • Why so pervert if there are regulars? - user207618

3 answers 3

 preg_replace('/([0-9]*)([.,])(0*)([1-9]{0,2}).*/', '$1$2$3$4', $myNumber); 

    since in your solution you work with numbers as strings, you can simply use regular expressions

     $data = [ 0.00025325, 0.0000000225, 0.02501, 0.1 ]; foreach($data as $d){ $str = number_format(10, $d, ',', '') ; if(preg_match('/(\d+)[.,]0*(\d{1,2})/', $str, $matches)){ print_r([$matches[0]]); } } 

    I will also propose a mathematical version without regulars (in this case, when the integer part is 0), but it is not quite accurate, it seems.

     foreach($data as $d){ $l = log10($d); print_r([ number_format($d, -floor($l)+1, ',', '') ]); } 
    • in square brackets do not need to screen the point - rjhdby
    • @rjhdby aha. but there is another problem, a long number is written in e . - teran
    • what is solved by preliminary formatting through number_format , as in the question of the author. - teran
    • yes number_format had to be used, thanks - Eugene Kolesnik
    • Did the guys have a problem with this function, if the number 335.000000000 arrives, it remains the same, how can it be corrected so that 335.00 remains in such cases? I use return preg_replace ('/ ([0-9] *) ([.,]) (0 *) ([1-9] {0,2}). * /', '$ 1 $ 2 $ 3 $ 4', number_format ( $ number, 10, ',', '')); - Evgeny Kolesnik

    I did it this way

      return preg_replace('/([0-9]*)([.,])(0*)([1-9]{0,2}).*/', '$1$2$3$4', number_format($number, 10, ',', ' '));