Round a number to a specific decimal place
From CodeCodex
| Image:Lightbulb.png Related content: |
| <DPL>
category=Math shownamespace=false </DPL> |
Contents |
[edit] Implementations
[edit] 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
[edit] OCaml
# open Printf;; # printf "%0.*f";; - : int -> float -> unit = <fun>
For example:
# printf "%0.*f\n" 1 1234.5678;; 1234.6 - : unit = ()
[edit] Perl
print sprintf "%0.*f", 2, 3456.67953;
[edit] 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
[edit] 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
[edit] 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
[edit] 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
[edit] Zsh
printf "%.0f\n" 1234567.899

