Skip to content

Commit

Permalink
Tipify copy-sign-to-number
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed Jun 2, 2024
1 parent 31326c1 commit c9151f8
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions content/snippets/js/s/copy-sign-to-number.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
---
title: Copy sign to number
type: snippet
title: Copy sign from one number to another in JavaScript
shortTitle: Copy sign to number
type: tip
language: javascript
tags: [math]
cover: cloudy-mountaintop
dateModified: 2020-10-07
excerpt: Copy the sign of one number to another without changing its absolute value.
dateModified: 2024-05-28
---

Returns the absolute value of the first number, but the sign of the second.
If you've ever worked extensively with numeric values, you might have stumbled upon a case where you need to **change the sign of a number**. This is relatively simple, but what if you want to **copy the sign** from another value. Naively, most of us would simply add a ternary operator and check if the second number is positive or negative, then do the same for the first number. But there's a much simpler way to do this.

- Use `Math.sign()` to check if the two numbers have the same sign.
- Return `x` if they do, `-x` otherwise.
In the simplest terms possible, either the target value has the correct sign (same as the source value) or it doesn't. All you really need to **compare are the signs** of the two numbers. If they're the same, you're done. If they're different, you just need to change the sign of the target value.

So how can that be done? Luckily, `Math.sign()` can help us out here. This methods returns either `1` (positive), `0` (zero), or `-1` (negative) depending on the sign of the number. By comparing the signs of the two numbers, we can easily determine if the sign needs to be changed.

The only thing left to do is use the ternary operator (`?`) to conditionally apply the unary `-` operator to the target value. If the signs are the same, the target value remains unchanged. If they're different, the **sign is flipped**.

```js
const copySign = (x, y) => Math.sign(x) === Math.sign(y) ? x : -x;
Expand Down

0 comments on commit c9151f8

Please sign in to comment.