size.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package common
  2. import (
  3. "fmt"
  4. "math/big"
  5. )
  6. type StorageSize float64
  7. func (self StorageSize) String() string {
  8. if self > 1000000 {
  9. return fmt.Sprintf("%.2f mB", self/1000000)
  10. } else if self > 1000 {
  11. return fmt.Sprintf("%.2f kB", self/1000)
  12. } else {
  13. return fmt.Sprintf("%.2f B", self)
  14. }
  15. }
  16. func (self StorageSize) Int64() int64 {
  17. return int64(self)
  18. }
  19. // The different number of units
  20. var (
  21. Douglas = BigPow(10, 42)
  22. Einstein = BigPow(10, 21)
  23. Ether = BigPow(10, 18)
  24. Finney = BigPow(10, 15)
  25. Szabo = BigPow(10, 12)
  26. Shannon = BigPow(10, 9)
  27. Babbage = BigPow(10, 6)
  28. Ada = BigPow(10, 3)
  29. Wei = big.NewInt(1)
  30. )
  31. //
  32. // Currency to string
  33. // Returns a string representing a human readable format
  34. func CurrencyToString(num *big.Int) string {
  35. var (
  36. fin *big.Int = num
  37. denom string = "Wei"
  38. )
  39. switch {
  40. case num.Cmp(Ether) >= 0:
  41. fin = new(big.Int).Div(num, Ether)
  42. denom = "Ether"
  43. case num.Cmp(Finney) >= 0:
  44. fin = new(big.Int).Div(num, Finney)
  45. denom = "Finney"
  46. case num.Cmp(Szabo) >= 0:
  47. fin = new(big.Int).Div(num, Szabo)
  48. denom = "Szabo"
  49. case num.Cmp(Shannon) >= 0:
  50. fin = new(big.Int).Div(num, Shannon)
  51. denom = "Shannon"
  52. case num.Cmp(Babbage) >= 0:
  53. fin = new(big.Int).Div(num, Babbage)
  54. denom = "Babbage"
  55. case num.Cmp(Ada) >= 0:
  56. fin = new(big.Int).Div(num, Ada)
  57. denom = "Ada"
  58. }
  59. // TODO add comment clarifying expected behavior
  60. if len(fin.String()) > 5 {
  61. return fmt.Sprintf("%sE%d %s", fin.String()[0:5], len(fin.String())-5, denom)
  62. }
  63. return fmt.Sprintf("%v %s", fin, denom)
  64. }