2016-02-25 42 views
0

我的代碼:轉換String對象,以浮動的Python

else: 
     revenue2 = revenue 
     stripLastLetter = revenue[len(revenue)-1:len(revenue)] 

     if stripLastLetter == "B": 
      result = revenue2[:-1] 
      revNum = float(result.replace(",", "")) 
      final = revNum * 1000000000 
      newnum = "{:0,.2f}".format(final) 
      #print(newnum) 
     elif stripLastLetter == "M": 
      result = revenue2[:-1] 
      revNum = float(result.replace(",", "")) 
      final = revNum * 1000000 
      newnum = "{:0,.2f}".format(final) 
      #print(newnum) 
     elif stripLastLetter == "K": 
      result = revenue2[:-1] 
      revNum = float(result.replace(",", "")) 
      final = revNum * 1000 
      newnum = "{:0,.2f}".format(final) 
      #print(newnum) 
     else: 
      result = revenue2 
      revNum = float(result.replace(",", "")) 
      final = revNum 
      newnum = "{:0,.2f}".format(final) 
      #print(newnum) 

     if float(newnum) > 50000000: 
      print(ticker.upper()+newnum) 
     else: 
      None 

在運行時,我的 「newnum」 變量是這樣的: 「56,100,000,000.00」 但仍字符串。

我在去年的if語句,我比較newnum爲int和我畫了一個錯誤:「不能把字符串轉換爲浮動:'30,270,000,000.00' 」

我怎麼能投newnum是一個浮動/ INT對象?

回答

0

這裏的問題是你的字符串中有逗號嘗試:

newint = float(newnum.replace(',','')) 
+0

但我的代碼第一條逗號,轉換爲浮動,然後添加逗號回來的.format功能。這個解決方案返回一個「不能轉換'浮動'對象到str隱式」對我來說「錯誤 –

+0

你可以打印你想要轉換的字符串像'print(newnum)' –

+0

是的,打印罰款 –