# How to round to certain numbers

What I want to do is be able to round all numbers below 0 to -1 and all other number to 1. So that no matter what the input is it becomes either 1 or -1.

• should an exact zero input yield 1? – george2079 Oct 21 '16 at 1:17
• It doesn't matter, I'm never rounding 0 – John Smith Oct 21 '16 at 1:29
• "It doesn't matter, I'm never rounding 0" — Well, then you just want the Sign of the numbers, no? I didn't suggest it because Sign[0] == 0 in Mathematica. – Szabolcs Oct 21 '16 at 23:16

Use

2 UnitStep[x] - 1


where x can be a number or any array of numbers.

If you never need to handle 0, use Sign.

Because the OP wrote "I'm never rounding 0", this will work fine:

Sign @ {-2, 0, 5}


{-1, 0, 1}

Issue with Sign[0] = 0:

sign[x_] := If[x == 0, 1, Sign[x]]


or

sign[x_] := Piecewise[{{Sign[x], x != 0}, {1, x == 0}}]


then

sign /@ {-2, 0, 5} (* not Listable though *)


{-1, 1, 1}

Usually not recommended:

Unprotect[Sign];
Sign[0] := 1
Protect[Sign];

Sign @ {-2, 0, 5}


{-1, 1, 1}

• (+1) But Sign is Listable... You can save a character! – kale Oct 21 '16 at 2:36
• Sign[0] gives the wrong result, tho... – Michael E2 Oct 21 '16 at 9:33
• Ah, I hate it when someone can't write what they mean. After all, "So that no matter what the input is it becomes either 1 or -1" is pretty darn clear. – Michael E2 Oct 21 '16 at 22:58

Like this?

             MyRounding[x_] = If[x < 0, -1, 1];


Examples:

             MyRounding[5]
MyRounding[-5]


give +1 and -1. Note that this rounds zero to 1.

x/Abs[x]


Conveniently doesn't work for $x=0$.