6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルサイズ表示に役立つgem filesize

Posted at

filesizeというgemを使ったので備忘録

148MBって何バイト?
13982730000バイトって何GB?

こんなときに使えるgem

  • 148MBをバイト単位に変換

Filesize.from("148MB").to_i
=> 148000000
  • 13982730000バイトをGB単位に変換

Filesize.from("13982730000 B").to_f('GB')
=> 13.98273

単位を指定せず、見やすい単位を自動で選んでもらうこともできる

  • 13982730000バイトを見やすい単位に変換

Filesize.from("13982730000 B").pretty
=> "13.02 GiB"

prettyを使うと、単位がKiB、MiB、GiBとなる

表示はMBやGBにしたいがどうしようと悩んでいたところ、先頭に書いたURLの内容を読んでいると以下の記載

(Filesize.from("1400 MB") + Filesize.from("1400 MiB")).pretty # => "2.87 GB"
(Filesize.from("1400 MiB") + Filesize.from("1400 MB")).pretty # => "2.67 GiB"

ということはこれでいけるのでは?と試したのがこちら


(Filesize.from("0 KB") + Filesize.from("13982730000 B")).pretty
=> "13.98 GB"

GB表示にすることができたが、注意点がいくつか

  • 小数第2位へ丸められる
  • 1GiB = 1024 * 1024 * 1024 byteだが、1GB = 1000 * 1000 * 1000 byteで計算される
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?