24
\$\begingroup\$

Round away from zero

Inspired by Round towards zero.

Given a number input via any reasonable method, round the number "away from zero" - positive numbers round up, and negative numbers round down.

If you intend to take the input as a string (via STDIN, for example), you should be able to handle numbers with or without the decimal point. If you take it as a number, it should at least be able to handle floating-point precision (double precision not required) or rational numbers.

You can output a floating-point number with the decimal point (e.g. 42.0) if desired. (Or even have some test cases output floating-point and some output integer, if it makes your answer shorter.)

Standard loopholes are not allowed, etc etc.

Test cases

-99.9 => -100
-33.5 => -34
-7    => -7
-1.1  => -2
0     => 0
2.3   => 3
8     => 8
99.9  => 100
42.0  => 42
-39.0 => -39

Sandbox Link

\$\endgroup\$
  • \$\begingroup\$ if we're taking numbers in a string context, such as STDIN, do we need to support the .0 as the test cases seem to suggest? \$\endgroup\$ – Jo King Sep 4 at 3:08
  • \$\begingroup\$ @JoKing yes-- I will update the question to clarify. This was actually the original case, but then people in the sandbox suggested adding non-decimal test cases so uh, here we are with both, sorry \$\endgroup\$ – Value Ink Sep 4 at 9:13
  • \$\begingroup\$ Feels good to be inspirational :) \$\endgroup\$ – connectyourcharger Sep 4 at 22:26
  • \$\begingroup\$ It's funny that all the languages that did so well on the previous challenge by taking integer input and integer output won't work so well, since they can't tell the difference between -0.1 and 0.1 \$\endgroup\$ – Jo King Sep 4 at 23:48

31 Answers 31

15
\$\begingroup\$

Excel, 13 bytes

=ROUNDUP(A1,)

Alternative

=EVEN(A1*2)/2
\$\endgroup\$
  • 4
    \$\begingroup\$ EVEN, what a strange function.. \$\endgroup\$ – tsh Sep 4 at 6:23
  • 13
    \$\begingroup\$ @tsh I think you mean "odd function". \$\endgroup\$ – negative seven Sep 5 at 4:47
  • 2
    \$\begingroup\$ @negativeseven Username checks out. :-P \$\endgroup\$ – Veky Sep 5 at 5:23
9
\$\begingroup\$

R, 32 bytes

x=scan()
sign(x)*ceiling(abs(x))
\$\endgroup\$
8
\$\begingroup\$

Jelly, 4 bytes

ĊṠ¡Ḟ

A monadic Link accepting a number which yields an integer.

Try it online! Or see a test-suite.

How?

ĊṠ¡Ḟ - Link: number, N
  ¡  - repeat...
 Ṡ   - ...number of times: sign of N (repeating -1 is the same as 0 times)
Ċ    - ...action: ceiling
   Ḟ - floor (that)
\$\endgroup\$
  • \$\begingroup\$ So how exactly does ¡ work for negative numbers? I don't think it's documented \$\endgroup\$ – caird coinheringaahing Sep 3 at 21:57
  • 1
    \$\begingroup\$ It's not documented on Jelly's wiki, but ¡s repetitive nature is implemented with a for index in range(repetitions) loop in the code. range([stop=]-1) is empty since start defaults to 0 and step defaults to 1 and "For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop." docs \$\endgroup\$ – Jonathan Allan Sep 3 at 22:18
  • \$\begingroup\$ ¡'s behavior relies on that of Python's range, and range(-1).__iter__().__next__() immediately throws StopIteration. \$\endgroup\$ – Unrelated String Sep 3 at 22:18
6
\$\begingroup\$

Python 3, 23 bytes

lambda i:i-i%(1|-(i>0))

Try it online!

-1 byte thanks to xnor

\$\endgroup\$
  • 1
    \$\begingroup\$ You can do (1|-(i>0)) to save a byte off (1,-1)[i>0]. \$\endgroup\$ – xnor Sep 4 at 7:06
  • \$\begingroup\$ @xnor Nice find, thanks! \$\endgroup\$ – Jitse Sep 4 at 7:23
  • \$\begingroup\$ Well done. I had it at 62 bytes ಥ_ಥ: g=lambda r:0if r==0 else(int(r)+r/abs(r)if r/int(r)!=1 else r) \$\endgroup\$ – user14492 Sep 4 at 10:41
  • \$\begingroup\$ What is the '|' before the '-'? \$\endgroup\$ – William Sep 4 at 22:13
  • 1
    \$\begingroup\$ @jaaq I really like that solution too! My initial approach was also 24 bytes. \$\endgroup\$ – Jitse Sep 6 at 15:43
5
\$\begingroup\$

Jelly, 5 4 bytes

AĊ×Ṡ

Try it online!

This ports recursive's Stax answer into Jelly, so check that answer out for an explanation.

-1 byte thanks to Nick Kennedy

Jelly, 6 5 bytes

ĊḞ>?0

Try it online!

-1 byte thanks to Jonathan Allan

How this one works

ĊḞ>?0 - Monadic link. Takes a float, x, as argument

   ?  - If:
  > 0 -   x > 0
      - Then:
Ċ     -   ceil(x)
      - Else:
 Ḟ    -   floor(x)
\$\endgroup\$
  • \$\begingroup\$ ĊḞ>?0 would work as your 6 does. \$\endgroup\$ – Jonathan Allan Sep 3 at 22:22
  • 1
    \$\begingroup\$ AĊ×Ṡ is 4 and functionally identical to your first answer. \$\endgroup\$ – Nick Kennedy Sep 3 at 23:15
  • \$\begingroup\$ @NickKennedy and Jonathan, thanks for the suggestions, they've been edited in \$\endgroup\$ – caird coinheringaahing Sep 4 at 7:45
5
\$\begingroup\$

Java (JDK), 18 bytes

d->d.setScale(0,0)

Try it online!

Explanations

Uses a BigDecimal as input and output. BigDecimal has a method setScale that sets the scale of the number. The first parameter is the number of digits after the dot separator, the second is the rounding mode. ROUND_UP is the "away-from-zero" rounding and has a value of 0 so I hardcode that value.

\$\endgroup\$
5
\$\begingroup\$

Vim, 36 bytes/keystrokes

:s/-/-<Space>
:g/\..*[1-9]/norm <C-v><C-a>lD
:s/<Space><cr>

Try it online! or Verify all Test Cases!

Explanation:

:s/             " Replace...
   -            "   A dash
    /-<Space>   "   With a dash and a space

:g/                             " On Every line matching this regex...
   \.                           "   A dot
     .*                         "   Followed By anything
       [1-9]                    "   Followed by a digit other than 0
            /norm               " Run the following keystrokes...
                  <C-v><C-a>    "   Increment the number by 1
                                "   This also conveniently places our cursor just before the dot
                            l   "   Move one character right
                             D  "   Delete everything after the cursor

:s/             " Replace...
   <Space>      "   A space
                "   (With nothing)
\$\endgroup\$
4
\$\begingroup\$

J, 6 bytes

**>.@|

Try it online!

Just a 1 character change from my answer on the cousin question.

\$\endgroup\$
4
\$\begingroup\$

C# (Visual C# Compiler), 41 bytes27 bytes24 bytes

s=>(int)s+Math.Sign(s%1)

Try it online!

First post here, had fun with it, hope u like it. Kinda felt C# place is empty here

-14 tnx to @expired data
-3 tnx to @night2

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site, and nice first answer! Hope you enjoy Code Golf! \$\endgroup\$ – caird coinheringaahing Sep 4 at 14:29
  • \$\begingroup\$ 27 bytes... Probably still a few to save \$\endgroup\$ – Expired Data Sep 4 at 15:10
  • \$\begingroup\$ @Expired, yea nice, this kind of coding was so weird at first glance that looks like I forgot about whole library thing, mind to post it as an answer \$\endgroup\$ – hessam hedieh Sep 4 at 19:08
  • 1
    \$\begingroup\$ @Night2, tnx for the comment, I didnt type the whole answer, I used the Code golf submission functionality, Just added a bit of my own words to the end, but for edit I just changed that code line, and u r right there, i forgot to update the link, which brings us back to the first step, to only modify once, kinda SOLID here, anyway, tnx for the hint too \$\endgroup\$ – hessam hedieh Sep 5 at 8:05
  • 1
    \$\begingroup\$ You've edited your TIO link to the 24 byte version, but the code line itself is still the 27 byte version. \$\endgroup\$ – Value Ink Sep 5 at 20:47
4
\$\begingroup\$

Runic Enchantments, 18 16 bytes

1µ-i:'-A{*+'.A@

Try it online!

"Adds" (away from zero) 0.999999 and floors the result. µ is the closest thing to an infinitesimal in language's operators. With a properly functioning Trunc(x) command, answer now supports 0 as input.

\$\endgroup\$
  • 1
    \$\begingroup\$ @JoKing Oof. Good catch. It's doing a divide by input to get the "sign" of the input value, which of course, divides by 0 when the input is 0. There's no (good) way around that right now. Will need this commit first. I'll poke Dennis (side benefit, the answer will get shorter). \$\endgroup\$ – Draco18s Sep 4 at 0:36
  • 1
    \$\begingroup\$ @JoKing Answer now handles 0 correctly. \$\endgroup\$ – Draco18s Sep 7 at 16:57
3
\$\begingroup\$

Stax, 6 bytes

å├╪∙Bß

Run and debug it

Procedure:

  1. Absolute value
  2. Ceiling
  3. Multiply by original sign
\$\endgroup\$
  • \$\begingroup\$ The tool I'm using says this is 14 bytes \$\endgroup\$ – Gust van de Wal Sep 5 at 22:02
  • \$\begingroup\$ Your tool is probably not aware of the stax character encoding. If you're still not convinced, in the "Tools" section, there's a download link, where you can actually download the source file and inspect its size for yourself. \$\endgroup\$ – recursive Sep 5 at 22:22
3
\$\begingroup\$

C, 94 43 39 bytes

thanks to ceilingcat for 39 bytes

#define f(n)(int)(n>0?ceil(n):floor(n))

TIO

\$\endgroup\$
  • \$\begingroup\$ 48 \$\endgroup\$ – ASCII-only Sep 5 at 2:34
2
\$\begingroup\$

Retina 0.8.2, 38 bytes

\.0+
.
\b9+\..
0$&
T`9d`d`.9*\..
\..*

Try it online! Link includes test cases. Explanation:

\.0+
.

Delete zeroes after the decimal point, to ensure that the number is not an integer; the next two matches fail if there are no digits after the decimal point.

\b9+\..
0$&

If the integer part is all 9s, prefix a 0 to allow the increment to overflow.

T`9d`d`.9*\..

Increment the integer part of the number.

\..*

Delete the fractional part of the number.

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 6 bytes

ÄîI.±*

A 5-byter should definitely be possible..

Try it online or verify all test cases.

Explanation:

Ä       # The absolute value of the (implicit) input,
 î      # ceiled
     *  # And then multiplied by
   .±   # the signum
  I     # of the input
        # (after which the result is output implicitly)
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 20 bytes

n=>n%1?n<0?~-n:-~n:n

Try it online!

Commented

n =>        // n = input
  n % 1 ?   // if n is not an integer:
    n < 0 ? //   if n is negative:
      ~-n   //     return -(floor(-n) + 1) = -floor(-n) - 1
    :       //   else:
      -~n   //     return -(-(floor(n) + 1)) = floor(n) + 1
  :         // else:
    n       //   return n unchanged
\$\endgroup\$
  • \$\begingroup\$ I was writing an answer for my 16-byte answer (n=>(~~n-n%1)%1+n) until I found out that my code didn't work for numbers between -1 and 1. You might be able to figure out how to make this work with the last 3 bytes there's left! \$\endgroup\$ – Gust van de Wal Sep 5 at 22:57
2
\$\begingroup\$

Perl 6, 18 bytes

{$_-.abs%-1*.sign}

Try it online!

Explanation

{                }  # Anonymous block
    .abs  # Absolute value
        %-1  # Modulo -1
           *.sign  # Multiply by sign
 $_-  # Subtract from original
\$\endgroup\$
2
\$\begingroup\$

MathGolf, 5 bytes

‼σ±ü*

Try it online!

Explanation

It's nice to find usage for the operator.

‼       apply next two operators to (implicit) input
 σ      sign (-1, 0, or 1)
  ±     absolute value
   ü    ceiling of that absolute value
    *   multiply the rounded absolute value with the sign
\$\endgroup\$
2
\$\begingroup\$

PHP, 30 bytes

<?=0^$argn-=0<=>fmod($argn,1);

Try it online!

If number is not integer, based on the sign -1 (for negative decimals) or 1 (for positive decimals) is added to it and then integer part of the new number is printed.


PHP, 32 bytes

<?=[ceil,floor][$argn<0]($argn);

Try it online!

Basically outputs floor of input if it is less than 0, else ceil of it.


PHP, 34 bytes

<?=($argn>0?:-1)*ceil(abs($argn));

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Brachylog, 7 bytes

⌋₁ℤ₁|⌉₁

Try it online!

or ⌉₁ℕ₁|⌋₁.

⌋₁         The input rounded down
  ℤ₁       is an integer less than -1
    |      and the output, or, the input
     ⌉₁    rounded up is the output.
\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 18 bytes

Sign@#⌈Abs@#⌉&

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 57 bytes

: f ( x -- x ) [ signum ] [ abs ceiling ] bi * >integer ;

Try it online!

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Unicode), 15 bytes

{⍎'⌈⌊'[0>⍵],⍕⍵}

Try it online!

Simple Dfn. Uses ⎕IO←0.

How:

{⍎'⌈⌊'[0>⍵],⍕⍵} ⍝ Main function, argument ⍵.
            ⍕⍵  ⍝ Stringified argument
           ,    ⍝ Appended to
      [0>⍵]     ⍝ This item... (0 if ⍵ is positive or 0, else 1)
  '⌈⌊'          ⍝ of this string (which are the functions Ceiling and Floor, respectively)
 ⍎              ⍝ Executed as APL code.
\$\endgroup\$
1
\$\begingroup\$

sed, 131 bytes + 2 bytes for -r flag

/^-?[^.]*(\.0*)?$/bQ
s/^(-?)9/\109/
s/([0-8]9*)\..*$/_\1/
h
s/.*_//
y/0123456789/1234567890/
G
s/(.*)\n(.*)_(.*)/\2\1/
:Q
s/\..*$//

Ungolfed

#!/bin/sed -rf

# identify integers
/^-?[^.]*(\.0*)?$/ b isInt

# add a leading 0 if we'll need it later
s/^(-?)9/\109/

# convert to format: -?[0-9]_[0-8]9*
s/([0-8]9*)\..*$/_\1/

# move the part that will remain constant into the hold buffer
h
s/.*_//

# [0-8]9* can be incremented via character substitution
y/0123456789/1234567890/

# reassemble parts
G
s/(.*)\n(.*)_(.*)/\2\1/

:isInt
# Get rid of anything after the decimal point
s/\..*$//
\$\endgroup\$
1
\$\begingroup\$

Perl 5 -pF/\./, 35 bytes

$_&&=$F[0]+($_!=int&&$_*(@F-1)/abs)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ fails 3.0. For switches, -pF\. is sufficient: the // are optional. \$\endgroup\$ – Oh My Goodness Sep 5 at 14:37
  • \$\begingroup\$ also 0.0 is true \$\endgroup\$ – Oh My Goodness Sep 5 at 14:51
  • \$\begingroup\$ Fixed both of those. \$\endgroup\$ – Xcali Sep 5 at 17:01
1
\$\begingroup\$

JavaScript (node.js), 30 23 21 bytes

s=>~~s+Math.sign(s%1)

Inspired by the C# answer.

Thanks to @Value Ink and @Gust van de Wal for -7 bytes!

Thanks again, @Gust van de Wal for another -2 bytes!

\$\endgroup\$
  • \$\begingroup\$ Why use += when + will do the trick in this case? -1 byte \$\endgroup\$ – Value Ink Sep 5 at 20:44
  • \$\begingroup\$ Instead of parseInt(), I'd just use ~~ at the start or another bitwise operator like |0 or ^0 at the end to save another chunk of bytes \$\endgroup\$ – Gust van de Wal Sep 5 at 23:08
  • \$\begingroup\$ @ValueInk wow, I have no idea why I wrote +=, thx for pointing it out \$\endgroup\$ – Sagittarius Sep 7 at 2:39
  • \$\begingroup\$ You can still drop the the outer parentheses \$\endgroup\$ – Gust van de Wal Sep 29 at 13:07
  • \$\begingroup\$ @GustvandeWal oh, I didn't know that! thanks \$\endgroup\$ – Sagittarius Oct 3 at 17:33
0
\$\begingroup\$

Perl 6, 19 bytes

{$_+|0+.sign*?/\./}

Try it online!

Not the shortest solution, but I'm working on it. Basically this truncates the number, then adds one away from zero if the number was not whole to begin with

\$\endgroup\$
0
\$\begingroup\$

Java (OpenJDK 8), 43 bytes

a->{return(int)((int)a/a<1?a>0?a+1:a-1:a);}

Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ The lambda function can be written without using an explicit return statement. \$\endgroup\$ – Joel Sep 3 at 23:58
  • \$\begingroup\$ @Joel is indeed right. And you can save 4 additional bytes changing the (int)a/a<1 to a%1!=0: 30 bytes \$\endgroup\$ – Kevin Cruijssen Sep 4 at 6:17
  • \$\begingroup\$ There's also the BigDecimal.setScale method that gives excellent results, like my answer demonstrates \$\endgroup\$ – Olivier Grégoire Sep 4 at 11:44
0
\$\begingroup\$

Japt, 6 bytes

Î*Ua c

Try it here

\$\endgroup\$
0
\$\begingroup\$

Red, 46 bytes

func[n][(pick[0 1]n = t: to 0 n)*(sign? n)+ t]

Try it online!

The slightly more readable version is 2 byte longer (those long function names!):

func[n][to 1(sign? n)* round/ceiling absolute n]
\$\endgroup\$
0
\$\begingroup\$

Scala, 16 bytes

_.setScale(0,UP)

Try it online!

Scala, 22 bytes

x=>x.signum*x.abs.ceil

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.