3
\$\begingroup\$

Task

Given a number between 0 and 1 and another integer, print the approximated value of the first number rounded off to the specified number of digits given by the second integer. For example, if the input is 0.3212312312 , 2 then the output is:

0.32

Rules

  • The number of digits after the dot should always equal the second input integer.

  • The input will always be ([)number from 0-1 , integer above 0(])

  • Predefined round functions are allowed.

  • The first input number will not have any trailing 0's

  • Always use a dot for input and output. Commas are not allowed.

  • Fractions are allowed as output with the notation number/number but try to just use a decimal notation.

[Trailing zero rule removed due to that i should have been faster]

  • Rounding should always be done to the closest number so up if above 4 and down if under 5.

Testcases

Input: 0.31231231231 , 1

Output: 0.3

Input: 0.1, 10

Output: 0.1000000000

Input: 0.01231231231 , 9

Output: 0.012312312

Scoring:

This is code-golf. Shortest answer in bytes wins.

Suggestion for making this challenge better are appreciated. Have fun golfing!

EDIT: definition of this challenge by Francisco Hahn: shortest way to round a float X with precision N on each language

\$\endgroup\$
  • \$\begingroup\$ Very closely related, potential duplicate. Since my vote is a hammer, I won't vote to close as yet. \$\endgroup\$ – AdmBorkBork Jun 6 '18 at 15:14
  • 1
    \$\begingroup\$ @AdmBorkBork as far as i see the other question handles significative values of the float, this one doesn't, but i can see this post as something like shortest way to round a float X with precision N on each language \$\endgroup\$ – Francisco Hahn Jun 6 '18 at 15:22
  • 2
    \$\begingroup\$ "Rounding should always be done to the closest number so up if above 4 and down if under 5." Most languages use the round-to-even standard (2.5 rounds to 2). If you enforce this requirement, I'm not sure any of the proposed solutions are correct. \$\endgroup\$ – Benjamin Jun 6 '18 at 16:13
  • 1
    \$\begingroup\$ Suggestion: test cases with rounding \$\endgroup\$ – Jo King Jun 6 '18 at 18:22
  • 1
    \$\begingroup\$ @12Me21: As noted on said answers, 0.02675 is not a "real" number; the actual value is 0.02674999999999..., so rounding down is correct here, regardless of rounding strategy. \$\endgroup\$ – ShadowRanger Jun 6 '18 at 18:58

22 Answers 22

6
\$\begingroup\$

APL (Dyalog Unicode), 1 byteSBCS

Anonymous tacit infix function (actually just a built-in). Takes number of decimals as left argument and fraction as right argument.

Try it online!

Documentation for dyadic ("Format By Specification").

\$\endgroup\$
  • 1
    \$\begingroup\$ I like how you treat that built-in so formally over TIO... \$\endgroup\$ – Erik the Outgolfer Jun 6 '18 at 17:07
  • 1
    \$\begingroup\$ I'm not sure if this fits the challenge as this requires a f as input instead of a , (atleast on TIO) \$\endgroup\$ – Luc H Jun 6 '18 at 19:37
  • \$\begingroup\$ @LucH APL is usually used in an interactive session (REPL). TIO's Code area contains the actual definition(s) while Input is the session where the "user" uses the function f. \$\endgroup\$ – Adám Jun 6 '18 at 20:03
5
\$\begingroup\$

JavaScript (Node.js), 18 bytes

a=>b=>a.toFixed(b)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ lol, this is just nice :) \$\endgroup\$ – Luc H Jun 6 '18 at 15:13
4
\$\begingroup\$

Japt, 2 bytes

xV

Try it online!

x is the builtin for rounding to n decimals. We pass in V (Second input).

\$\endgroup\$
  • 1
    \$\begingroup\$ Okay... I don't think this can be beat lol. \$\endgroup\$ – Luc H Jun 6 '18 at 15:19
  • \$\begingroup\$ Dang it! Too slow! \$\endgroup\$ – Shaggy Jun 6 '18 at 15:22
  • \$\begingroup\$ tio.run/##y0osKPn/vyLs/38DPQNDI2MoUtBRMAIA maybe use that notation for input in your tio as your current version wasn't according to the challenge rules. (code is the same, just changed the input) \$\endgroup\$ – Luc H Jun 6 '18 at 15:23
  • 2
    \$\begingroup\$ @LucH - that's irrelevant in Japt each comma or newline separated item is a separate input. \$\endgroup\$ – Shaggy Jun 6 '18 at 15:26
  • \$\begingroup\$ Fails on 0.02675, 4 \$\endgroup\$ – 12Me21 Jun 6 '18 at 18:29
4
\$\begingroup\$

Japt, 2 bytes

Takes input as an array of 2 numbers.

rx

Try it

reduces the array by rounding the first number to the number of decimals specified by the second.

\$\endgroup\$
  • \$\begingroup\$ Japt just seems to be too good for this challenge. \$\endgroup\$ – Luc H Jun 6 '18 at 15:25
  • \$\begingroup\$ Upvoting this answer because it is smaller than the other Japt answer: this one uses only lowercase characters. \$\endgroup\$ – Jeff Jun 6 '18 at 20:31
2
\$\begingroup\$

PHP, 28 Bytes

Try it online

Code

<?=round($argv[0],$argv[1]);
\$\endgroup\$
2
\$\begingroup\$

PHP, 47 39 bytes

function a($b,$c){return round($b,$c);}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ How many languages are you going to golf this in? ;) \$\endgroup\$ – Luc H Jun 6 '18 at 15:16
  • \$\begingroup\$ @LucH 2 is nothing try seeing Leaky's 10 answer combo :D \$\endgroup\$ – HyperNeutrino Jun 6 '18 at 15:16
  • \$\begingroup\$ @LucH The challenge is too easy. xD sorry \$\endgroup\$ – Luis felipe De jesus Munoz Jun 6 '18 at 15:17
  • \$\begingroup\$ @LuisfelipeDejesusMunoz codegolf.stackexchange.com/questions/120052/… that one was easy and it blew up so that's why i also made this one. \$\endgroup\$ – Luc H Jun 6 '18 at 15:19
  • \$\begingroup\$ Are you sure you can pass the arguments like that toa php script?, it is my understanding that the values has to be on the $argv array as arguments for the script. \$\endgroup\$ – Francisco Hahn Jun 6 '18 at 15:44
2
\$\begingroup\$

Python 3 (produces rounded float, no trailing zeroes), 5 bytes

round

Try it online!

Python's built-in round function is defined to do exactly what the OP wants in the summary edited in later "round a float X with precision N", though without appending trailing zeroes (because it's still returning a float, and floats don't include information about their formatting).

Python 3 (produces string form), 16 bytes

'{:.{}f}'.format

Try it online!

Formatting operations can use a nested specifier to allow one argument to define the precision of the other. Doesn't print it, but returns a formatted string with the specified precision.

Python 3 (prints string), 30 bytes

lambda a,b:print(f'{a:.{b}f}')

Try it online!

Python 3.6+ f-strings save some characters here (couldn't use them without the wrapping function since we wouldn't know the names to use). Mostly included to demonstrate f-strings (obviously longer than other solutions).

\$\endgroup\$
  • \$\begingroup\$ Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information. \$\endgroup\$ – 12Me21 Jun 6 '18 at 18:25
  • 2
    \$\begingroup\$ @12Me21: This is a problem in any language based on IEEE binary floating point. If 2.675 doesn't really exist, it's just a shorter spelling of 2.6749999999999999996 or whatever, then you've rounded correctly. Python isn't unique here, it's just up front about the problem in the docs, where many languages don't bother to mention it. \$\endgroup\$ – ShadowRanger Jun 6 '18 at 18:37
2
\$\begingroup\$

Python 2, 24 bytes

-4 bytes thanks to ovs

lambda a,b:"%%0.%sf"%b%a

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Fails on 0.02675, 4 \$\endgroup\$ – 12Me21 Jun 6 '18 at 18:36
  • 1
    \$\begingroup\$ @12Me21: Not relevant, since 0.02675 doesn't actually exist as an exact value in IEEE 754 binary64 floating point (which most languages use as the basis for floating point math; you'll get the same issues with Java, JavaScript, C#, C [compiler dependent], etc.). The closest value is something like 0.02674999999999999947, with 0.02675 being a convenient shorthand. Floating point math is broken from a human perspective \$\endgroup\$ – ShadowRanger Jun 6 '18 at 18:53
  • 1
    \$\begingroup\$ 24 bytes \$\endgroup\$ – ovs Jun 7 '18 at 1:49
  • \$\begingroup\$ @ovs: Using more modern formatting (i.e. the str.format method, not printf-style formatting), you can get it down to 16 bytes (doesn't even require a lambda). My second solution for Python 3 will work identically in Python 2.7 (and only require two more bytes on Python 2.6, to add indices to the formatting placeholders). \$\endgroup\$ – ShadowRanger Jun 7 '18 at 14:59
1
\$\begingroup\$

Forth (gforth), 26 bytes

Assuming decimal is on top of the floating point stack and precision is on the integer stack

: f dup 2 + swap 1 f.rdp ;

Try it online!

Explanation

f.rdp takes a float and 3 arguments from the integer stack:

  1. the width of the output (answer uses n+2 to account for 0 and decimal point)
  2. the number of digits after the decimal (answer uses n)
  3. the required number of significant figures in the input (answer uses 1, because floats with less significant figures are outputted in exponential notation)

Code explanation

dup 2 + swap 1        \ place n+2 n and 1 on top of the stack
f.rdp                 \ formats output
\$\endgroup\$
1
\$\begingroup\$

Stax, 1 bytes

j

Run and debug it

In stax, j is a built-in instruction that performs the required rounding.

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

T-SQL, 24 bytes

SELECT STR(f,20,d)FROM t

Per our input standards, input is taken via pre-existing table t with float f and integer d.

The function STR() is shorter and more convenient than either a CAST or a ROUND.

You didn't specify, so I assumed that 20 digits would be more than sufficient. If not, that hard-coded value can be increased.

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

Java (JDK 10), 21 bytes

n->d->n.setScale(d,4)

Try it online!

I would have loved to have submitted n->n::setScale (14 bytes) but alas, there is no default rounding, so we get ArithmeticException when rounding is required...

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

MATL, 13 bytes

i'%.'j'f'hhYD

Try it online!

Explanation:

i              % Grab first input: 0.32315
 '%.'j'f'      % Push the literal: ['%.' second input as string 'f'], where the input
               % specifies the number of decimals
         YD    % printf('%.sf',x)  where s is the second input, and x is the first
\$\endgroup\$
  • \$\begingroup\$ hh seems to be missing from the explanation. Also, I think you can remove i if you change the input order \$\endgroup\$ – Luis Mendo Jun 7 '18 at 22:07
1
\$\begingroup\$

R, 40 36 bytes

function(x,n)format(round(x,n),ns=n)

Try it online!

(-4) thanks to digEmAll

\$\endgroup\$
  • 1
    \$\begingroup\$ You can use partial matching for arguments, i.e. nsmall=n can be shortened to ns=n \$\endgroup\$ – digEmAll Jun 7 '18 at 9:35
1
\$\begingroup\$

Julia 0.6, 51 bytes

(x,d)->(y=string(round(x, d));y*"0"^(d-endof(y)+2))

Try it online!

With trailing zeros as per the questions's "Trailing zeroes should be added with for example 0.1, 10" condition.

Julia's @printf can only take constant X values in %.Xf format strings (%.4f, etc.), so instead this code manually pads the required number of zeros if the rounded value has less than d digits after the decimal place.

First, store the rounded number as a string in y. Then, the number of digits after decimal point in y is length(y) - 2 (- 2 because the inputs are between 0 and 1, so there's one initial digit and then a decimal point to subtract). endof(y) is just a shorter way to write length(y) (at least for Julia v0.6).

Then, subtract this from the required number of digits d. Then, (d-(endof(y)-2)) (= (d-endof(y)+2)) tells you how many digits are missing in the output (if any). Use that in "0"^(d-endof(y)+2) to get "0" repeated that many times, and then append that to y with the string * (concatenate) operator.


Julia 0.6, 5 bytes

round

Try it online!

Without trailing zeros, conforming to the summary "shortest way to round a float X with precision N on each language".

\$\endgroup\$
  • \$\begingroup\$ Could you use two printf like this 43 bytes R solution? \$\endgroup\$ – JayCe Jun 7 '18 at 17:52
  • 1
    \$\begingroup\$ Doesn't seem possible, unfortunately. The problem is that Julia's @printf parses its format string at compile time (for doing some type system magic), and as such requires the whole format string to be a compile-time constant. There are external packages to allow C-style or Python-style full-fledged format strings, but nothing builtin as of now. \$\endgroup\$ – sundar - Reinstate Monica Jun 7 '18 at 18:04
  • \$\begingroup\$ Thanks for the clarification - I get now what you meant by constant above. Too bad! \$\endgroup\$ – JayCe Jun 7 '18 at 18:18
0
\$\begingroup\$

74 Bytes Python 2.7

lambda x,y:str(x)[:y+2]if int(str(x)[y+2])<5else float(str(x)[:y+2])+.1**y

Messy but I think it works for all the scenarios.

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

Perl 6, 18 bytes

{$^a.base(10,$^b)}

Try it

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

05AB1E, 10 bytes

.ò0¹²g-Ì∍J

is the builtin that already gives the answer for most test cases. 0¹²g-Ì∍J is to correctly append trailing zeroes if necessary.

Try it online.

.ò          # Round the second decimal input to the integer first input amount of decimals
            #  i.e. 10 and 0.1 → 0.1
            #  i.e. 1 and 0.67231 → 0.7
0           # Literal '0'
 ¹          # Get the first integer input
  ²g        # Get the length of the second decimal input
    -       # Subtract them from each other
     Ì      # Increase it by 2 for the "0." part
            #  i.e. 10 and 0.1 → 10-3+2 → 9
            #  i.e. 1 and 0.67231 → 1-7+2 → -8
      ∍     # Extend the "0" to a size of that length
            #  i.e. "0" and 9 → "000000000"
            #  i.e. "0" and -8 → ''
       J    # Join everything together
            #  i.e. 0.1 and "000000000" → 0.1000000000
            #  i.e. 0.7 and '' → 0.7
\$\endgroup\$
0
\$\begingroup\$

Octave, 28 bytes

@(x,y)printf(['%.',y,'f'],x)

Try it online!

Takes the first input as a number and the second as a string. Creates a formatting string: %.yf by concatenation, where y is the input that specifies the number of decimals. x is the input number that will be printed.

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

R, 42 bytes

function(x,n)sprintf(paste0("%.",n,"f"),x)

Try it online!

Failed attempt at outgolfing DS_UNI's shorter R answer.

Even worse:

R, 43 bytes

function(x,n)sprintf(sprintf("%%.%if",n),x)

Try it online!

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

Kotlin, 19 bytes

"%.${b}f".format(a)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ By default, submissions should be either a function or a full program. This is just a snippet that needs predefined variables a and b. \$\endgroup\$ – Jo King Jun 9 '18 at 13:22
0
\$\begingroup\$

Tcl, 31 bytes

proc R x\ n {format %.*f $n $x}

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.