C# CopySign()

Anonymous contributor's avatar
Anonymous contributor
Published Nov 15, 2025
Contribute to Docs

The Math.CopySign() method in C# returns a value that combines the magnitude of the first argument with the sign of the second. It’s useful for matching the sign of one number to another while keeping the original magnitude.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours

Syntax

Math.CopySign(double x, double y)

Parameters:

  • x (double): The value whose magnitude (absolute value) will be used.
  • y (double): The value whose sign will be applied to the result.

Return value:

  • Returns a double value with the magnitude of x and the sign of y.
  • If x is NaN, the result is NaN.
  • If y is NaN, the result is treated as if y were positive.

Example: Adjusting Velocity Based on Direction

In this example, Math.CopySign() is used to adjust a projectile’s velocity so that its direction matches a steering input:

using System;
public class CopySignExample
{
public static void Main()
{
double projectileSpeed = 18.75;
double steeringDirection = -0.5; // Negative indicates reverse direction
double adjustedVelocity = Math.CopySign(projectileSpeed, steeringDirection);
Console.WriteLine($"Adjusted velocity: {adjustedVelocity}");
}
}

This program outputs:

Adjusted velocity: -18.75

Codebyte Example: Standardizing Numeric Sign Alignment

In this example, Math.CopySign() ensures a set of magnitudes follow given directional signs, even when the sign is NaN:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C# on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours