Pretty file size in Ruby?

后端 未结 7 1883
半阙折子戏
半阙折子戏 2020-12-13 20:06

I\'m trying to make a method that converts an integer that represents bytes to a string with a \'prettied up\' format.

Here\'s my half-working attempt:



        
7条回答
  •  猫巷女王i
    2020-12-13 20:14

    Here is a method using log10:

    def number_format(n)
       n2 = Math.log10(n).to_i / 3
       return '%.3f' % (n / 1e3 ** n2) + ['', ' k', ' M', ' G'][n2]
    end
    
    s = number_format(9012345678e0)
    puts s == '9.012 G'
    

    https://ruby-doc.org/core/Math.html#method-c-log10

提交回复
热议问题