新手问题 [已解决] 请教个小问题,用 float 保存的数值,但如果 1.0, 希望只显示为 1,怎么办?

chairy11 · 2014年10月15日 · 最后由 yehualiu 回复于 2014年10月15日 · 2781 次阅读

问题

额,这种问题又不知道怎么 google 了。 我是用 float 保存的,因为偶尔是会有 1.5 之类的数。但绝大多数的时候是整数。所以看着满目的 1.0, 2.0, 3.0, 看着别扭。 怎样才能让它,如果小数点后有数值,就显示为 float,比如 1.5, 就显示为 1.5.如果小数点后面没有值,就显示为整数? 难道要先判断 if self.to_i == self 吗?

解决方案

方案一(#3 楼@gihnius 提供)

format: %g
sprintf("%g", 1.5) => "1.5"
sprintf("%g", 1.0) => "1"

(解决方案由,非常感谢!)

方案二(#10 楼 @lgn21st 提供)

"%g" % 1.5 => "1.5"
"%g" % 1.0 => "1"

谢谢各位:)

这个 format: %g sprintf("%g", 1.5) => "1.5" sprintf("%g", 1.0) => "1"

1.0 1.5

1.5 1 2.5 2

你不觉得小数位相同要漂亮的多么?

#include <stdio.h>
int main(void){
  printf("%.0f\n", 1.0);
  return 0;
}
puts "%.0f" % 1.0

#5 楼 @huobazi 不啊,因为 1.5 是少数,绝大多数显示为 x.0,我觉得从大脑解读速度来看,就好像要下降很多。

#3 楼 @gihnius 这个好棒!就这个了!谢谢:)

#6 楼 @yehualiu 额,我看不懂,先借用 3 楼 @gihnius 的解决方案了……谢谢哈~

好多年都没有写过 sprintf 了,应该简写成下面这样就可以了吧?

"%g" % 1.5 => "1.5"
"%g" % 1.0 => "1"

#10 楼 @lgn21st 牛!虽然没看太懂……

#10 楼 @lgn21st 第一次了解了此方法,学习啦....

str % arg  new_str Link
   #Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string.

   "%05d" % 123                              #=> "00123"
   "%-5s: %08x" % [ "ID", self.object_id ]   #=> "ID   : 200e14d6"
   "foo = %{foo}" % { :foo => 'bar' }        #=> "foo = bar"
需要 登录 后方可回复, 如果你还没有账号请 注册新账号