PHP – How to get the square root of an arbitrary precision number using bcsqrt() function?

In PHP, the bcsqrt() function is used to get the square root of an arbitrary precision number. It accepts the arbitrary precision number as a string and gives the square root of the number after scaling the result to the specified precision.

Syntax

string bcsqrt($num_string, $scale)

Parameters

The bcsqrt() function accepts two different parameters: $num_string and $scale.

  • $num_string − It represents the number whose square root to be evaluated. It is a string-type parameter.

  • $scale − It indicates the number of digits that appear after the decimal point in the output. This parameter is optional.

Return Value

The bcsqrt() function returns the square root of the number as a string.

Example 1

Calculate square root without specifying scale value ?

<?php
   // input numbers with arbitrary precision
   $num_string = "22";

   // below bcsqrt function calculates the square root
   $result = bcsqrt($num_string);
   echo "Output without scale value: ", $result;
?>
Output without scale value: 4

Example 2

Calculate square root with specified scale value ?

<?php
   // input numbers with arbitrary precision
   $num_string = "22";

   // scale value 3
   $scale = "3";

   // below bcsqrt function calculates the square root
   $result = bcsqrt($num_string, $scale);
   echo "Output with scale value: ", $result;
?>
Output with scale value: 4.690

Example 3

Working with larger precision numbers ?

<?php
   // input very large precision number
   $large_number = "123456789.987654321";
   $scale = 6;

   $result = bcsqrt($large_number, $scale);
   echo "Square root of $large_number is: ", $result;
?>
Square root of 123456789.987654321 is: 11111.111071

Conclusion

The bcsqrt() function provides precise square root calculations for arbitrary precision numbers. Use the scale parameter to control the number of decimal places in the result.

Updated on: 2026-03-15T09:54:48+05:30

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements