Round a number to a specific decimal place

From CodeCodex

Revision as of 04:03, 30 May 2007 by 201.167.81.61 (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 = ()

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)
    (let ((div (expt 10 precision)))
         (/ (round (* number div)) div)))

For example:

* (round-to 1234.4567 0)
1234
* (round-to 1234.4567 1)
2469/2
* (float *)
1234.5
* (round-to 1234.4567 2)
61723/50
* (float *)
1234.46
* (round-to 1234.4567 3)
1234457/1000
* (float *)
1234.457