Last active
August 15, 2025 08:41
-
-
Save mrk21/5434713779760ec107eb0c80878dd16a to your computer and use it in GitHub Desktop.
Convert real number to human readable number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class HumanReadableNumber | |
| attr_reader :b, :u_n | |
| def initialize(b:, u_n:) | |
| @b = b | |
| @u_n = u_n | |
| end | |
| def from(a) | |
| _E = [u_n.size-1, Math.log([1, a.abs].max, b).floor].min | |
| u = u_n[_E] | |
| f = (a.to_f / b**_E).round(2) | |
| f_d = (f - f.floor) | |
| f = f.to_i if f_d < 0.01 | |
| "#{f}#{u}" | |
| end | |
| end | |
| jnumber = HumanReadableNumber.new(b: 10000, u_n: ["","万","億","兆"]) | |
| jnumber.from(2350) #=> "2350" | |
| jnumber.from(1_2350) #=> "1.24万" | |
| jnumber.from(123_0000_0000) #=> "123億" | |
| byte = HumanReadableNumber.new(b: 1024, u_n: %w(B KB MB GB TB)) | |
| byte.from(1023) #=> "1023B" | |
| byte.from(1024) #=> "1KB" | |
| byte.from(160_300_000_000) #=> "149.29GB" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.