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

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 166330; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
18
  • \$\begingroup\$ Very closely related, potential duplicate. Since my vote is a hammer, I won't vote to close as yet. \$\endgroup\$ Commented Jun 6, 2018 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\$ Commented Jun 6, 2018 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
    Commented Jun 6, 2018 at 16:13
  • 1
    \$\begingroup\$ Suggestion: test cases with rounding \$\endgroup\$
    – Jo King
    Commented Jun 6, 2018 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\$ Commented Jun 6, 2018 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\$
3
  • 1
    \$\begingroup\$ I like how you treat that built-in so formally over TIO... \$\endgroup\$ Commented Jun 6, 2018 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
    Commented Jun 6, 2018 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
    Commented Jun 6, 2018 at 20:03
5
\$\begingroup\$

JavaScript (Node.js), 18 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ lol, this is just nice :) \$\endgroup\$
    – Luc H
    Commented Jun 6, 2018 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\$
7
  • 1
    \$\begingroup\$ Okay... I don't think this can be beat lol. \$\endgroup\$
    – Luc H
    Commented Jun 6, 2018 at 15:19
  • \$\begingroup\$ Dang it! Too slow! \$\endgroup\$
    – Shaggy
    Commented Jun 6, 2018 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
    Commented Jun 6, 2018 at 15:23
  • 2
    \$\begingroup\$ @LucH - that's irrelevant in Japt each comma or newline separated item is a separate input. \$\endgroup\$
    – Shaggy
    Commented Jun 6, 2018 at 15:26
  • \$\begingroup\$ Fails on 0.02675, 4 \$\endgroup\$
    – 12Me21
    Commented Jun 6, 2018 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\$
2
  • \$\begingroup\$ Japt just seems to be too good for this challenge. \$\endgroup\$
    – Luc H
    Commented Jun 6, 2018 at 15:25
  • \$\begingroup\$ Upvoting this answer because it is smaller than the other Japt answer: this one uses only lowercase characters. \$\endgroup\$
    – Jeff
    Commented Jun 6, 2018 at 20:31
2
\$\begingroup\$

PHP, 47 39 bytes

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

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ How many languages are you going to golf this in? ;) \$\endgroup\$
    – Luc H
    Commented Jun 6, 2018 at 15:16
  • \$\begingroup\$ @LucH 2 is nothing try seeing Leaky's 10 answer combo :D \$\endgroup\$
    – hyperneutrino
    Commented Jun 6, 2018 at 15:16
  • \$\begingroup\$ @LucH The challenge is too easy. xD sorry \$\endgroup\$ Commented Jun 6, 2018 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
    Commented Jun 6, 2018 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\$ Commented Jun 6, 2018 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\$
2
  • \$\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
    Commented Jun 6, 2018 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\$ Commented Jun 6, 2018 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\$
4
  • \$\begingroup\$ Fails on 0.02675, 4 \$\endgroup\$
    – 12Me21
    Commented Jun 6, 2018 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\$ Commented Jun 6, 2018 at 18:53
  • 1
    \$\begingroup\$ 24 bytes \$\endgroup\$
    – ovs
    Commented Jun 7, 2018 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\$ Commented Jun 7, 2018 at 14:59
1
\$\begingroup\$

PHP, 28 Bytes

Try it online

Code

<?=round($argv[0],$argv[1]);
\$\endgroup\$
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\$
0
1
\$\begingroup\$

Stax, 1 bytes

j

Run and debug it

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

\$\endgroup\$
0
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\$
1
  • \$\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
    Commented Jun 7, 2018 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
  • 1
    \$\begingroup\$ You can use partial matching for arguments, i.e. nsmall=n can be shortened to ns=n \$\endgroup\$
    – digEmAll
    Commented Jun 7, 2018 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\$
3
  • \$\begingroup\$ Could you use two printf like this 43 bytes R solution? \$\endgroup\$
    – JayCe
    Commented Jun 7, 2018 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 R
    Commented Jun 7, 2018 at 18:04
  • \$\begingroup\$ Thanks for the clarification - I get now what you meant by constant above. Too bad! \$\endgroup\$
    – JayCe
    Commented Jun 7, 2018 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\$
2
  • \$\begingroup\$ Welcome to PPCG! :) \$\endgroup\$
    – Shaggy
    Commented Jun 6, 2018 at 16:12
  • \$\begingroup\$ It fails if the y is greater than the precision of x: tio.run/##PYzBCsIwEETvfsVSCGTTUJqCl2K/… \$\endgroup\$
    – wastl
    Commented Jun 6, 2018 at 16:20
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\$
1
  • \$\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
    Commented Jun 9, 2018 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 and acknowledge you have read our privacy policy.

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