Go math.Copysign
Combine the size of one value with the sign of another.
A simple example
math.Copysign
- Start with Magnitude 2, sign from −1
- Do this Copy just the sign
- Result −2
package main
import "fmt"
import "math"
func main() {
fmt.Println(math.Copysign(2.0, -1.0))
}
-2
Syntax
math.Copysign(magnitude, direction)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goApply a refund direction to an amount
A payment system stores an amount separately from whether it is a charge or a refund. Reuse the amount's magnitude while applying the direction belonging to the current transaction.
package main
import (
"fmt"
"math"
)
func main() {
magnitude := 7.0
direction := -1.0
fmt.Printf("%.3f\n", math.Copysign(magnitude, direction))
}
-7.000
A refund direction makes the seven-unit adjustment negative.
Label a return transaction
A cashier has a receipt amount of 24 credits and a negative return indicator. The journal uses the indicator to set the sign on the amount.
Using 24 · -1 gives -24 for this measurement.
Restore a forward dial reading
A dial service receives a magnitude of twelve and a positive direction flag. It reconstructs the signed reading for the display.
Using 12 · 1 gives 12 for this measurement.
What to watch for
Some numeric formats distinguish negative zero from positive zero, including when used as the sign source.