Board logo

标题: [转载代码] [PowerShell每日技巧]转换数字格式(20140305) [打印本页]

作者: DAIC    时间: 2014-3-6 13:19     标题: [PowerShell每日技巧]转换数字格式(20140305)

Often, users need to format numbers and limit the number of digits, or add leading zeros. There is one simple and uniform strategy for this: the operator "-f"!

Let's make sure a number has leading zeros:

PS C:\> $number = 68
PS C:\> '{0:d7}' -f $number
0000068


This will produce a 7-digit number with leading zeros. Adjust the number after "d" to control the number of digits.

To limit the number of digits, use "n" instead of "d". This time, the number after "n" controls the number of digits:

PS C:\> $number = 35553568.67826738
PS C:\> '{0:n1}' -f $number
35,553,568.7


Likewise, use "p" to format percentages:

PS C:\> $number = 0.32562176536
PS C:\> '{0:p2}' -f $number
32.56 %


http://powershell.com/cs/blogs/tips/archive/2014/03/05/formatting-numbers-easily.aspx
作者: Batcher    时间: 2014-3-6 14:56

# Dec to Hex
PS C:\> $number = 255
PS C:\> '{0:X0}' -f $number
FF

# Thousands Separators
PS C:\> $number = 1234567
PS C:\> '{0:n0}' -f $number
1,234,567

# Currency
PS C:\> $number = 35553568.67826738
PS C:\> '{0:c1}' -f $number
$35,553,568.7
作者: DAIC    时间: 2014-3-7 16:57

左侧补零的另外一种方式:
PS C:\> $number = '68'
PS C:\> $number.PadLeft(7, '0')
0000068




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2