Question10:浮點數轉有效精度浮點數的字符串(Python)

涉及到數據統計,浮點數的有效精度是經常用到的。浮點數小數後面的位數是不定的,跟平臺相關。大多時候,對於我們的數據顯示是沒有多大用處的。所以需要去掉,並轉化成字符串顯示。

# -*- coding: utf-8 -*-
#!/usr/bin/env python
# author: mrn6
import math
import time
import random

def get_specific_precision(float_number, precision=2):
      precision_match = int(math.pow(10, precision))
      return int(float_number * precision_match)/precision_match

def get_specific_precision_string(float_number, precision=2):
      #float_number_string=str(float_number)
      #if float_number_string.endswith('.0'):
      #    return int(float_number)
      result_number = get_specific_precision(float_number, precision)
      return str(result_number)

def test(test_times=10000):
      started=time.time()
      results=[]
      for i in range(test_times):
           results.append(get_specific_precision_string(random.uniform(100000000, 999999999), 7))
      ended=time.time()
      print('test '+str(test_times)+' times in '+str(get_specific_precision_string(ended-started, 6))+' s')
      #for i in results:
             #print(i)
      return results

test()
test(100000)
test(1000000)

效率結果:
 

python float浮點數轉化有效精度浮點數字符串效率

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章