Round a number to a specific decimal place

From CodeCodex

Revision as of 13:28, 2 October 2009 by 86.70.175.84 (Talk)

Related content:

Implementations

C

<HIGHLIGHTSYNTAX language="c">

  1. 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;

} </HIGHLIGHTSYNTAX>

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

OCaml

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

For example:

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

Perl

<HIGHLIGHTSYNTAX language="perl"> print sprintf "%0.*f", 2, 3456.67953; </HIGHLIGHTSYNTAX>

PHP

<highlightsyntax language="php3"><?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 ?> </highlightsyntax> Original source: PHP Manual

Python

<highlightsyntax language="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 </highlightsyntax>

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

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

Zsh

printf "%.0f\n" 1234567.899