36
\$\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\$
4
  • \$\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
    Commented Sep 4, 2019 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
    Commented Sep 4, 2019 at 9:13
  • \$\begingroup\$ Feels good to be inspirational :) \$\endgroup\$
    – moltarze
    Commented Sep 4, 2019 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
    Commented Sep 4, 2019 at 23:48

39 Answers 39

17
\$\begingroup\$

Excel, 13 bytes

=ROUNDUP(A1,)

Alternative

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

R, 32 bytes

x=scan()
sign(x)*ceiling(abs(x))
\$\endgroup\$
2
  • 3
    \$\begingroup\$ 31 bytes -- very nice answer! \$\endgroup\$
    – Giuseppe
    Commented Sep 3, 2019 at 21:40
  • 1
    \$\begingroup\$ 25 bytes \$\endgroup\$ Commented Sep 5, 2019 at 6:53
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\$
3
  • \$\begingroup\$ So how exactly does ¡ work for negative numbers? I don't think it's documented \$\endgroup\$ Commented Sep 3, 2019 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\$ Commented Sep 3, 2019 at 22:18
  • \$\begingroup\$ ¡'s behavior relies on that of Python's range, and range(-1).__iter__().__next__() immediately throws StopIteration. \$\endgroup\$ Commented Sep 3, 2019 at 22:18
6
\$\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\$
6
\$\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\$
1
5
\$\begingroup\$

Python 3, 23 bytes

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

Try it online!

-1 byte thanks to xnor

\$\endgroup\$
8
  • 1
    \$\begingroup\$ You can do (1|-(i>0)) to save a byte off (1,-1)[i>0]. \$\endgroup\$
    – xnor
    Commented Sep 4, 2019 at 7:06
  • \$\begingroup\$ @xnor Nice find, thanks! \$\endgroup\$
    – Jitse
    Commented Sep 4, 2019 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
    Commented Sep 4, 2019 at 10:41
  • \$\begingroup\$ What is the '|' before the '-'? \$\endgroup\$
    – user80602
    Commented Sep 4, 2019 at 22:13
  • 1
    \$\begingroup\$ @jaaq I really like that solution too! My initial approach was also 24 bytes. \$\endgroup\$
    – Jitse
    Commented Sep 6, 2019 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\$
3
  • \$\begingroup\$ ĊḞ>?0 would work as your 6 does. \$\endgroup\$ Commented Sep 3, 2019 at 22:22
  • 1
    \$\begingroup\$ AĊ×Ṡ is 4 and functionally identical to your first answer. \$\endgroup\$ Commented Sep 3, 2019 at 23:15
  • \$\begingroup\$ @NickKennedy and Jonathan, thanks for the suggestions, they've been edited in \$\endgroup\$ Commented Sep 4, 2019 at 7:45
4
\$\begingroup\$

Stax, 6 bytes

å├╪∙Bß

Run and debug it

Procedure:

  1. Absolute value
  2. Ceiling
  3. Multiply by original sign
\$\endgroup\$
2
  • \$\begingroup\$ The tool I'm using says this is 14 bytes \$\endgroup\$ Commented Sep 5, 2019 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
    Commented Sep 5, 2019 at 22:22
4
\$\begingroup\$

J, 6 bytes

**>.@|

Try it online!

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

\$\endgroup\$
4
\$\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\$
1
  • \$\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\$ Commented Sep 5, 2019 at 22:57
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\$
9
  • 1
    \$\begingroup\$ Welcome to the site, and nice first answer! Hope you enjoy Code Golf! \$\endgroup\$ Commented Sep 4, 2019 at 14:29
  • \$\begingroup\$ 27 bytes... Probably still a few to save \$\endgroup\$ Commented Sep 4, 2019 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\$ Commented Sep 4, 2019 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\$ Commented Sep 5, 2019 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
    Commented Sep 5, 2019 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\$
2
  • 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\$ Commented Sep 4, 2019 at 0:36
  • 1
    \$\begingroup\$ @JoKing Answer now handles 0 correctly. \$\endgroup\$ Commented Sep 7, 2019 at 16:57
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\$
1
  • \$\begingroup\$ 48 \$\endgroup\$
    – ASCII-only
    Commented Sep 5, 2019 at 2:34
3
\$\begingroup\$

Husk, 5 bytes

*±¹⌈a

Try it online! Just takes the sign of the input times the ceiling of its absolute value.

\$\endgroup\$
1
  • \$\begingroup\$ Alternative 5-byter: ?⌊⌈<0 \$\endgroup\$ Commented Oct 18, 2020 at 16:50
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\$

Wolfram Language (Mathematica), 18 bytes

Sign@#⌈Abs@#⌉&

Try it online!

\$\endgroup\$
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\$

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\$
3
  • \$\begingroup\$ fails 3.0. For switches, -pF\. is sufficient: the // are optional. \$\endgroup\$ Commented Sep 5, 2019 at 14:37
  • \$\begingroup\$ also 0.0 is true \$\endgroup\$ Commented Sep 5, 2019 at 14:51
  • \$\begingroup\$ Fixed both of those. \$\endgroup\$
    – Xcali
    Commented Sep 5, 2019 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\$
6
  • \$\begingroup\$ Why use += when + will do the trick in this case? -1 byte \$\endgroup\$
    – Value Ink
    Commented Sep 5, 2019 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\$ Commented Sep 5, 2019 at 23:08
  • \$\begingroup\$ @ValueInk wow, I have no idea why I wrote +=, thx for pointing it out \$\endgroup\$ Commented Sep 7, 2019 at 2:39
  • \$\begingroup\$ You can still drop the the outer parentheses \$\endgroup\$ Commented Sep 29, 2019 at 13:07
  • \$\begingroup\$ @GustvandeWal oh, I didn't know that! thanks \$\endgroup\$ Commented Oct 3, 2019 at 17:33
1
\$\begingroup\$

PowerShell Core, 45 38 37 bytes

[int]("$args"-replace'\.0*[^0]','.9')

Try it online!

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

PowerShell Core, 54 48 bytes

$a,$u=$args-split'\.'
(1,-1)[2*!+$u+($a-lt0)]+$a

Try it online!

Thanks @mazzy for the improved golfing !

Original implementation

$a,$u="$args"|% s*t '.'
(((1,-1)[$a-lt0]+$a),$a)[!+$u]

Try it online!

Explanations

$a,$u="$args"|% s*t '.'        # splits the input as a string using '.'
                        [!+$u] # if there are no decimals
(                   ,$a)       # return the int part as is
 ((1,-1)[$a-lt0]+$a)           # return the int part + or - one depending of the sign of the input
\$\endgroup\$
1
1
\$\begingroup\$

Julia 1.0, 17 bytes

Save 6 bytes thanks to the awesome comments of MarcMush!

x->x+sign(x%=1)-x

Try it online!

An alternative with 22 bytes

x->sign(x)ceil(abs(x))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Thanks! I didn't know the %= that can be very useful in codegolf \$\endgroup\$
    – Tanj
    Commented May 2, 2021 at 20:42
1
+50
\$\begingroup\$

Vyxal r, 5 4 bytes

Built-ins I previously didn't know existed FTW!

ȧ⌈∆±

Try it Online!

Explanation:

      # Implicit input
ȧ     # Absolute value
 ⌈    # Ceiling
  ∆±  # Change to the sign of input
      # Implicit output
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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