gpt4 book ai didi

ruby-on-rails - ruby 中的字节到兆字节

转载 作者:数据小太阳 更新时间:2023-10-29 06:56:32 26 4
gpt4 key购买 nike

在 javascript(或 coffeescript)中,我有以下功能:

bytesToMegabytes = (bytes) ->
return Math.round((b/1024/1024) * 100) / 100

我正在尝试用 ruby​​ 重新创建它。我有:

def bytes_to_megabytes (bytes)
(((bytes.to_i/1024/1024) * 100) / 100).round
end

但这轮不同?例如,1153597 在 ruby​​ 代码中变为 1。

最佳答案

我不想成为一个自作聪明的人,但似乎没有人注意到这里的计算困惑。 1 兆字节就是 1000000 字节 ( google it )。 1024 是关于 10^2 字节(即 1024 KB)的过时混淆。自 1998 年以来,这已被称为千比字节 (wiki),现在已成为常态。

这意味着您只需将字节除以 1000000 即可。我添加了一些舍入以获得额外的有用性:

def bytes_to_megabytes (bytes)
(bytes.to_f / 1000000).round(2)
end
puts bytes_to_megabytes(1153597) # outputs 1.15

关于ruby-on-rails - ruby 中的字节到兆字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com