Difference between revisions of "Round a number to a specific decimal place"

From CodeCodex

Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 +
===C===
 +
<pre>
 +
string format(double Value, int nPrecision)
 +
  {
 +
    char buffer[100]; //Buffer where to store the resulting formatted string.
 +
  sprintf(buffer,"%0.*f",nPrecision,Value); //Print formatted data to a string
 +
  return (string)buffer;
 +
}
 +
</pre>
 +
 +
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: [http://www.daniweb.com/techtalkforums/thread33133.html Ancient Dragon]
 +
 +
===OCaml===
 +
<pre>
 +
# open Printf;;
 +
# printf "%0.*f";;
 +
- : int -> float -> unit = <fun>
 +
</pre>
 +
For example:
 +
<pre>
 +
# printf "%0.*f\n" 1 1234.5678;;
 +
1234.6
 +
- : unit = ()
 +
</pre>
 
===Ruby===
 
===Ruby===
 
<pre>
 
<pre>
Line 29: Line 58:
  
 
Original source: [http://programmingishard.com/posts/show/128 rbates]
 
Original source: [http://programmingishard.com/posts/show/128 rbates]
 
===C===
 
<pre>
 
string format(double Value, int nPrecision)
 
  {
 
    char buffer[100]; //Buffer where to store the resulting formatted string.
 
  sprintf(buffer,"%0.*f",nPrecision,Value); //Print formatted data to a string
 
  return (string)buffer;
 
}
 
</pre>
 
 
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: [http://www.daniweb.com/techtalkforums/thread33133.html Ancient Dragon]
 
  
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 
[[Category:C]]
 
[[Category:C]]
 
[[Category:Math]]
 
[[Category:Math]]

Revision as of 23:30, 1 August 2006

Implementations

C

string format(double Value, int nPrecision)
   {
    char buffer[100]; //Buffer where to store the resulting formatted string.
   sprintf(buffer,"%0.*f",nPrecision,Value); //Print formatted data to a string
   return (string)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

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