4
0

price.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package strconv
  2. // AppendPrice will append an int64 formatted as a price, where the int64 is the price in cents.
  3. // It does not display whether a price is negative or not.
  4. func AppendPrice(b []byte, price int64, dec bool, milSeparator byte, decSeparator byte) []byte {
  5. if price < 0 {
  6. if price == -9223372036854775808 {
  7. x := []byte("92 233 720 368 547 758 08")
  8. x[2] = milSeparator
  9. x[6] = milSeparator
  10. x[10] = milSeparator
  11. x[14] = milSeparator
  12. x[18] = milSeparator
  13. x[22] = decSeparator
  14. return append(b, x...)
  15. }
  16. price = -price
  17. }
  18. // rounding
  19. if !dec {
  20. firstDec := (price / 10) % 10
  21. if firstDec >= 5 {
  22. price += 100
  23. }
  24. }
  25. // calculate size
  26. n := LenInt(price) - 2
  27. if n > 0 {
  28. n += (n - 1) / 3 // mil separator
  29. } else {
  30. n = 1
  31. }
  32. if dec {
  33. n += 2 + 1 // decimals + dec separator
  34. }
  35. // resize byte slice
  36. i := len(b)
  37. if i+n > cap(b) {
  38. b = append(b, make([]byte, n)...)
  39. } else {
  40. b = b[:i+n]
  41. }
  42. // print fractional-part
  43. i += n - 1
  44. if dec {
  45. for j := 0; j < 2; j++ {
  46. c := byte(price%10) + '0'
  47. price /= 10
  48. b[i] = c
  49. i--
  50. }
  51. b[i] = decSeparator
  52. i--
  53. } else {
  54. price /= 100
  55. }
  56. if price == 0 {
  57. b[i] = '0'
  58. return b
  59. }
  60. // print integer-part
  61. j := 0
  62. for price > 0 {
  63. if j == 3 {
  64. b[i] = milSeparator
  65. i--
  66. j = 0
  67. }
  68. c := byte(price%10) + '0'
  69. price /= 10
  70. b[i] = c
  71. i--
  72. j++
  73. }
  74. return b
  75. }