使用数字 [英] Working with digits

查看:35
本文介绍了使用数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对 % 标记前的模式进行解释:

("%012d" % 10)

% 操作符在这其中的作用是什么?

解决方案

需要先看 Kernel#sprtintf :

格式序列的语法如下.

 %[flags][width][.precision]type

<块引用>

格式序列由一个百分号、后跟可选标志、宽度和精度指示符组成,然后以字段类型字符结尾.字段类型控制如何解释相应的 sprintf 参数,而标志则修改该解释.

字段宽度是一个可选的整数,后跟可选的句点和精度.宽度指定将写入此字段结果的最小字符数.

现在来看你的例子:"%012d" % 10.

"%012d" 称为格式字符串.type d 表示 - 将参数转换为十进制数.012 表示您指定 12 作为将写入此字段结果的最少字符数.

现在看String的文档#%

<块引用>

Format——使用str作为格式规范,并返回应用到arg的结果.如果格式规范包含多个替换,则 arg 必须是包含要替换的值的数组或哈希.有关格式字符串的详细信息,请参阅 Kernel::sprintf.

I need an explanation for the pattern before the % mark in:

("%012d" % 10)

What is the role of % operator in this?

解决方案

Need to look first Kernel#sprtintf :

The syntax of a format sequence is follows.

 %[flags][width][.precision]type

A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.

Now coming to your example : "%012d" % 10.

"%012d" called format string. The type d means - Convert argument as a decimal number. 012 means you are specifying 12 as a minimum number of characters that will be written to the result for this field.

Now look at the documentation of String#%

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.

这篇关于使用数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆