PHP – How to multiply two arbitrary precision numbers using bcmul() function?

In PHP, bcmul() function is used to multiply two arbitrary precision numbers. This function is particularly useful when dealing with very large numbers or when you need precise decimal calculations that exceed PHP's floating-point precision limits.

Syntax

string bcmul(string $num1, string $num2, ?int $scale = null)

Parameters

The bcmul() function accepts three parameters −

  • $num1 − The left operand as a string representing an arbitrary precision number.

  • $num2 − The right operand as a string representing an arbitrary precision number.

  • $scale − Optional integer parameter that sets the number of decimal places in the result. If not provided, it uses the default scale set by bcscale() or 0.

Return Value

The bcmul() function returns the multiplication result as a string.

Example 1 − Basic Multiplication Without Scale

Let's multiply two numbers without specifying a scale value −

<?php
    // Two input numbers using arbitrary precision
    $num_string1 = "10.5552";
    $num_string2 = "3";
    
    // Calculate multiplication without scale parameter
    $result = bcmul($num_string1, $num_string2);
    
    echo "Output without scale: " . $result;
?>
Output without scale: 31

Without the scale parameter, the digits after the decimal point are discarded.

Example 2 − Multiplication With Scale

Here, we use the same input values with a scale value of 4 −

<?php
    // Two input numbers using arbitrary precision
    $num_string1 = "10.5552";
    $num_string2 = "3";
    
    // Set scale value to 4
    $scaleVal = 4;
    
    // Calculate multiplication with scale parameter
    $result = bcmul($num_string1, $num_string2, $scaleVal);
    echo "Output with scale 4: " . $result;
?>
Output with scale 4: 31.6656

Example 3 − Large Number Multiplication

Demonstrating multiplication of very large numbers −

<?php
    // Multiplying large numbers
    $large_num1 = "123456789012345678901234567890";
    $large_num2 = "987654321098765432109876543210";
    
    $result = bcmul($large_num1, $large_num2, 2);
    echo "Large number multiplication: " . $result;
?>
Large number multiplication: 121932631137021795226185032733622923332237463801111263526900.00

Conclusion

The bcmul() function is essential for accurate multiplication of arbitrary precision numbers in PHP. Use the scale parameter to control decimal precision in your calculations.

Updated on: 2026-03-15T09:53:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements