Ruby四舍五入的函数

ruby使用round函数实现四舍五入。下面的函数可以实现在四舍五入时保留指定位数的小数:

1
2
3
4
5
6
7
8
9
10
11
12
#i 原始数 n 要保留的小数位数,flag=1 四舍五入 flag=0 不四舍五入  
def f(i,n,flag)  
  y = 1  
  n.times do |x|  
    y = y*10  
  end  
  if flag==1  
   (i*y).round/(y*1.0)  
  else  
  (i*y).floor/(y*1.0)  
  end  
end

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

Related Posts

Leave a Reply

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

About Me

About Me
Record Technical Articles at Gooss.org.

Entries (RSS) and Comments (RSS). Valid XHTML and CSS and XFN.

© Copyright 2009 山海经. All rights reserved.

Social Bookmarks

Copyright © Designed by: Free WP Templates
Food Charts |  About Breast Milk |  Organic Food