2012-02-27 18 views
3

我想將數字格式化爲百分比,小數點後至少有兩位數字;此外至少有一位有效數字。格式字符串語法:至少包含一個有效數字的打印百分比

例如,我想0.123456看起來像'12 .34%';和0.0000看起來像'0.0001%'。

有沒有簡單的方法來實現這一目標?

原因是我的標準輸出應該是點後的2位小數的定點數;但如果數量是如此之小,它看起來像0.00%,我需要拿出至少一個顯著位,因此可以從真正的0

回答

2

如果您將百分比包裝在課程中,則可以使用格式方法執行操作,並仍將其用於正常計算。你也可以解析arguement到格式(之間的部分:在 '{1:3}' 和},覆蓋at_least值:

import sys 
import math 

class Percentage(float): 
    _at_least = 2 
    def __init__(self, val): 
     self._x = val 

    def __format__(self, s): 
     #print 's [%s]' % (repr(s)) 
     at_least = Percentage._at_least 
     try: 
      at_least = int(s) 
     except: 
      pass 
     return '{1:.{0}%}'.format(max(at_least, int(-math.log10(self._x))-1), 
            self._x) 

for x in (1., .1, .123456, .0123, .00123, .000123, .0000123, .00000123): 
    p = Percentage(x) 
    print '{0} {1:3} {2}'.format(x, p, 50 * p) 

輸出:

1.0 100.000% 50.0 
0.1 10.000% 5.0 
0.123456 12.346% 6.1728 
0..230% 0.615 
0.0.123% 0.0615 
0.00.012% 0.00615 
1.23e-05 0.001% 0.000615 
1.23e-06 0.0001% 6.15e-05 

你可以爲at_least做一些更巧妙的解析,以指定字段寬度,對齊方式等。

9
import math 

def format_percent(x, at_least=2): 
    return '{1:.{0}%}'.format(max(at_least, int(-math.log10(x))-1), x) 


for x in (1., .1, .123456, .0123, .00123, .000123, .0000123, .00000123): 
    print x, format_percent(x, 2) 


1.0 100.00% 
0.1 10.00% 
0.123456 12.35% 
0..23% 
0.0.12% 
0.00.01% 
1.23e-05 0.001% 
1.23e-06 0.0001% 

更多情況來區分不同的at_least

>>> format_percent(.1, 3) 
'10.000%' 

>>> format_percent(., 5) 
'1.23457%' 

>>> format_percent(.000123, 0) 
'0.01%' 

>>> format_percent(1.23456, 0) 
'123%' 
+3

+1 - 非常整潔的解決方案。沒有意識到你可以嵌套格式說明符那樣小問題 - 你需要''輸入數學''在使用之前。 – Blair 2012-02-27 07:50:41

+0

@Blair - 謝謝,'math' importe d現在。 – eumiro 2012-02-27 07:54:00

+1

我假設當我真的需要在一個大的'print'語句中使用時,我必須這樣做:'print('答案是{total.format(format_percent(fraction)))''中的{}據推測,沒有辦法擴展標準的語言來添加這種特殊的格式? – max 2012-02-27 16:37:05

相關問題