w3resource

PHP Math Exercises: Convert scientific notation to an int and a float

PHP math: Exercise-4 with Solution

Write a PHP script to convert scientific notation to an int and a float.

Sample scientific notation : 4.5e3

Sample Solution:

PHP Code:

<?php
$val = '4.5e3'; // Assign a string containing a number in scientific notation ('4.5e3') to the variable $val
$ival = (int) $val; // Convert the string $val to an integer and store it in $ival
$fval = (float) $val; // Convert the string $val to a float and store it in $fval
echo $ival."\n"; // Output the integer value stored in $ival followed by a newline character ("\n")
echo $fval."\n"; // Output the float value stored in $fval followed by a newline character ("\n")
?>

Output:

4                                                           
4500

Explanation:

In the exercise above,

  • $val = '4.5e3';: This line assigns the string '4.5e3' to the variable $val. This string represents the number 4500 in scientific notation (4.5 * 10^3).
  • $ival = (int) $val;: This line converts the string $val to an integer and stores the result in the variable $ival. When casting a string to an integer, PHP converts it to an integer if possible. In this case, it truncates the fractional part and converts '4.5e3' to the integer 4500.
  • $fval = (float) $val;: This line converts the string $val to a float and stores the result in the variable $fval. When casting a string to a float, PHP interprets the string as a floating-point number. In this case, it converts '4.5e3' to the float 4500.0.
  • echo $ival."\n";: This line outputs the integer value stored in $ival, followed by a newline character ("\n").
  • echo $fval."\n";: This line outputs the float value stored in $fval, followed by a newline character ("\n").

Flowchart :

Flowchart: Convert scientific notation to an int and a float

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to generate random 11 characters string of letters and numbers.
Next: Write a PHP script to convert a date from yyyy-mm-dd to dd-mm-yyyy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.