Skip to content

Instantly share code, notes, and snippets.

@mrk21
Last active August 15, 2025 08:41
Show Gist options
  • Select an option

  • Save mrk21/5434713779760ec107eb0c80878dd16a to your computer and use it in GitHub Desktop.

Select an option

Save mrk21/5434713779760ec107eb0c80878dd16a to your computer and use it in GitHub Desktop.
Convert real number to human readable number
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"
@mrk21
Copy link
Author

mrk21 commented Aug 13, 2025

  • $a$: real number $$a \in \mathbb{R}$$
  • $F$: significand $$F \in \mathbb{R}$$
  • $b$: base $$b \in \mathbb{N}^+$$
  • $E$: exponent $$b \in \mathbb{N}$$
  • ${u_n}$: unit numerical sequence
  • $h$: human readable number $$F + u_n$$ (e.g. $$1.32 + \rm{MB}$$)
$$\begin{align} \{u_n\} &= \rm{B}, \rm{KB}, \rm{MB}, \rm{GB}, \rm{TB} \\\ \mathbb{H} &= \{ r + u \; | \; r \in \mathbb{R},\; u \in \{u_n\} \} \\\ a &= F b^E \\\ b &= 1024 \\\ E &= \min\{|\{u_n\}|-1,\; \lfloor \log_b \max\{1, |a|\} \rfloor\} \\\ F &= \frac{a}{b^E} \\\ F_r &= \frac{\lceil 10^2 F \rfloor}{10^2} \\\ h &= F_r + u_E,\; h \in \mathbb{H} \\\ \end{align}$$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment