skip to Main Content

I have a number 3.43E-6 and I need to convert it into 0.00000343. Is that possible with PHP?

I tried PHP number_format and also tried using the answer of this post (float), but it does not work as expected. The mentioned number is not a string but a decimal value, and by the answer mentioned in that post we can get the normal whole number from positive exponential values (5.78e5, 3.14e5), but not working for the negative exponential values like 3.43E-6, 6.24464e-7, 5.864e-5. It returns the same value that we give as an input if we use a negative exponential value.

Number: 3.43E-6

Expected result: 0.00000343

2

Answers


  1. Chosen as BEST ANSWER

    Using the answers provided, I created a function like the one below, which seems to be working fine.

    function convertExponentialToDecimal($number) {
    
      $full_string = $number;
      $num_string_without_dollar = str_replace('$', '', $full_string);
    
      $is_exponential = preg_match('/^$?[+-]?d+(.d+)?[Ee][+-]?d+$/i', $num_string_without_dollar); // check if the number is in exponential notation
      if ($is_exponential) {
        
          $decimal = sprintf("%.20f", $num_string_without_dollar);
          $decimal = bcmul($decimal, '1', 20);
          $decimal = rtrim($decimal, '0');
          $decimal = rtrim($decimal, '.');
    
      } else {
          $decimal = (float)$num_string_without_dollar;
      }
    
      return $decimal;
    
    }
    

    This function can convert the exponential values to a whole number (in decimal notation).

    echo convertExponentialToDecimal('6.20503e-7');
    

    The above code gives a result of 0.000000620503.

    I don't know if this is the proper solution or not; however, it is working correctly.

    Thank you all!


  2. yes it is possible try this and you can modify this 8 if u want more decimal '%.8f

    $number = 3.43E-6;
    $decimal = sprintf('%.8f', $number);
    echo '$' . $decimal; // output: $0.00000343
    

    also this is another example

    $decimal = sprintf('%.10f', $number);
    echo '$' . $decimal; // output: $0.0000034300
    

    there is other way of doing this :

    $converted_number = number_format($number, 8, '.', '');
    echo $converted_number; // Output: 0.00000343
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search