ruby-on-rails – Rails:如何以百分比打印小数?
发布时间:2020-12-16 21:28:05 所属栏目:百科 来源:网络整理
导读:有没有办法以百分比的形式打印十进制数,所以只能在句点后面的两位数字? 我的小数总是在1到0之间,所以我想可以从第三个字符开始调用number.round(2),但是我找不到任何地方的语法. 为了澄清,我想要将数字存储为一个完整的十进制,但是以百分比打印. 解决方法
有没有办法以百分比的形式打印十进制数,所以只能在句点后面的两位数字?
我的小数总是在1到0之间,所以我想可以从第三个字符开始调用number.round(2),但是我找不到任何地方的语法. 为了澄清,我想要将数字存储为一个完整的十进制,但是以百分比打印. 解决方法
你可能要使用number_to_percentage方法.这里有一些如何使用它的例子.
number_to_percentage(100) # => 100.000% number_to_percentage("98") # => 98.000% number_to_percentage(100,precision: 0) # => 100% number_to_percentage(1000,delimiter: '.',separator: ',') # => 1.000,000% number_to_percentage(302.24398923423,precision: 5) # => 302.24399% number_to_percentage(1000,locale: :fr) # => 1 000,000% number_to_percentage("98a") # => 98a% number_to_percentage(100,format: "%n %") # => 100 % 选项: :locale - Sets the locale to be used for formatting (defaults to current locale). :precision - Sets the precision of the number (defaults to 3). :significant - If true,precision will be the # of significant_digits. If false,the # of fractional digits (defaults to false). :separator - Sets the separator between the fractional and integer digits (defaults to “.”). :delimiter - Sets the thousands delimiter (defaults to “”). :strip_insignificant_zeros - If true removes insignificant zeros after the decimal separator (defaults to false). :format - Specifies the format of the percentage string The number field is %n (defaults to “%n%”). 或者你可以写一些如下的ruby: class Numeric def percent_of(n) self.to_f / n.to_f * 100.0 end end p (1).percent_of(10) # => 10.0 (%) p (200).percent_of(100) # => 200.0 (%) p (0.5).percent_of(20) # => 2.5 (%) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 为什么我的C代码看不到这个C#类成员?
- 如何解决XML5619: 文档语法不正确
- objective-c – 如何将xcdatamodel文件转换为xcdatamodeld文
- 在Cascades和CoreNative之间,两个主要的黑莓手册C框架,更容
- error: xml2-config not found. Please check your libxml2
- React-native bundle command generated old main.jsbundle
- ruby-on-rails – 从_form或controller保存的当前用户ID
- 如何利用Cocos2d-x开发一个游戏?
- Pipeline和Gridsearch并行化调参简介
- Swift 4:使用Codable`通用参数’T’无法推断