size.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package common
  17. import (
  18. "fmt"
  19. "math/big"
  20. )
  21. type StorageSize float64
  22. func (self StorageSize) String() string {
  23. if self > 1000000 {
  24. return fmt.Sprintf("%.2f mB", self/1000000)
  25. } else if self > 1000 {
  26. return fmt.Sprintf("%.2f kB", self/1000)
  27. } else {
  28. return fmt.Sprintf("%.2f B", self)
  29. }
  30. }
  31. func (self StorageSize) Int64() int64 {
  32. return int64(self)
  33. }
  34. // The different number of units
  35. var (
  36. Douglas = BigPow(10, 42)
  37. Einstein = BigPow(10, 21)
  38. Ether = BigPow(10, 18)
  39. Finney = BigPow(10, 15)
  40. Szabo = BigPow(10, 12)
  41. Shannon = BigPow(10, 9)
  42. Babbage = BigPow(10, 6)
  43. Ada = BigPow(10, 3)
  44. Wei = big.NewInt(1)
  45. )
  46. //
  47. // Currency to string
  48. // Returns a string representing a human readable format
  49. func CurrencyToString(num *big.Int) string {
  50. var (
  51. fin *big.Int = num
  52. denom string = "Wei"
  53. )
  54. switch {
  55. case num.Cmp(Ether) >= 0:
  56. fin = new(big.Int).Div(num, Ether)
  57. denom = "Ether"
  58. case num.Cmp(Finney) >= 0:
  59. fin = new(big.Int).Div(num, Finney)
  60. denom = "Finney"
  61. case num.Cmp(Szabo) >= 0:
  62. fin = new(big.Int).Div(num, Szabo)
  63. denom = "Szabo"
  64. case num.Cmp(Shannon) >= 0:
  65. fin = new(big.Int).Div(num, Shannon)
  66. denom = "Shannon"
  67. case num.Cmp(Babbage) >= 0:
  68. fin = new(big.Int).Div(num, Babbage)
  69. denom = "Babbage"
  70. case num.Cmp(Ada) >= 0:
  71. fin = new(big.Int).Div(num, Ada)
  72. denom = "Ada"
  73. }
  74. // TODO add comment clarifying expected behavior
  75. if len(fin.String()) > 5 {
  76. return fmt.Sprintf("%sE%d %s", fin.String()[0:5], len(fin.String())-5, denom)
  77. }
  78. return fmt.Sprintf("%v %s", fin, denom)
  79. }