Round a number to a specific decimal place

From CodeCodex

Revision as of 07:14, 7 December 2010 by 211.2.129.92 (Talk)

Related content:

Implementations

C

#include <stdlib.h>
/* Don't forget to free()! the result after using it.
   This code actually truncates instead of rounding values */
char* format(double Value, int nPrecision)
{
   char *buffer = malloc(128*sizeof(char)); //Buffer where to store the resulting formatted string.
   snprintf(buffer,127,"%0.*f",nPrecision,Value); //Print formatted data to a string
   return buffer;
}

For example:

format( 3456.67953, 1 ) results in 3456.6
format( 3456.67953, 2 ) results in 3456.67
format( 3456.67953, 3 ) results in 3456.679

Original source: Ancient Dragon

Common Lisp

(defun round-to (number precision &optional (what #'round))
    (let ((div (expt 10 precision)))
         (/ (funcall what (* number div)) div)))

The optional parameter "what" can be one of

#'floor
#'ceil
#'truncate
#'round ;;No need to, though.

For example:

* (round-to 1234.4567 0)
1234
* (round-to 1234.4567 1)
2469/2
* (float *)
1234.5
* (round-to -1234.4567 2 #'floor)
-61723/50
* (float *)
-1234.46
* (round-to 1234.4567 3 #'truncate)
154307/125
* (float *)
1234.456

Erlang

is_prime(N) when N < 2 -> false;
is_prime(N) when N =:= 2; N =:= 3 -> true;
is_prime(N) when N rem 2 =:= 0; N rem 3 =:= 0 -> false;
is_prime(N) ->
    Limit = isqrt(N),           % integer square root of number
    is_prime(N, 5, Limit, 2).

is_prime(_, I, Limit, _) when I > Limit     -> true;
is_prime(N, I,     _, _) when N rem I =:= 0 -> false;
is_prime(N, I, Limit, Inc) ->
    is_prime(N, I+Inc, Limit, 6-Inc).

OCaml

# open Printf;;
# printf "%0.*f";;
- : int -> float -> unit = <fun>

For example:

# printf "%0.*f\n" 1 1234.5678;;
1234.6
- : unit = ()

Perl

print sprintf "%0.*f", 2, 3456.67953;

PHP

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

Original source: PHP Manual

Python

print round(3.4)         # 3
print round(3.5)         # 4
print round(3.6)         # 4
print round(3.6, 0)      # 4
print round(1.95583, 2)  # 1.96
print round(1241757, -3) # 1242000
print round(5.045, 2)    # 5.05
print round(5.055, 2)    # 5.06

Ruby

class Float
  def round_to(x)
    (self * 10**x).round.to_f / 10**x
  end

  def ceil_to(x)
    (self * 10**x).ceil.to_f / 10**x
  end

  def floor_to(x)
    (self * 10**x).floor.to_f / 10**x
  end
end

For example:

num = 138.249
num.round_to(2)
# => 138.25
num.floor_to(2)
# => 138.24
num.round_to(-1)
# => 140.0

Original source: rbates

Note: Since Ruby 1.9, rounding can be achieved with: [1]

num.round(precision) # 1.23456.round(4) == 1.2346

Zsh

printf "%.0f\n" 1234567.899