earn_format.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "info/channel_statistics/earn/earn_format.h"
  8. namespace Info::ChannelEarn {
  9. using EarnInt = Data::EarnInt;
  10. constexpr auto kMinorPartLength = 9;
  11. constexpr auto kMaxChoppedZero = kMinorPartLength - 2;
  12. constexpr auto kZero = QChar('0');
  13. constexpr auto kDot = QChar('.');
  14. QString MajorPart(EarnInt value) {
  15. const auto string = QString::number(value);
  16. const auto diff = int(string.size()) - kMinorPartLength;
  17. return (diff <= 0) ? QString(kZero) : string.mid(0, diff);
  18. }
  19. QString MinorPart(EarnInt value) {
  20. if (!value) {
  21. return QString(kDot) + kZero + kZero;
  22. }
  23. const auto string = QString::number(value);
  24. const auto diff = int(string.size()) - kMinorPartLength;
  25. const auto result = (diff < 0)
  26. ? kDot + u"%1"_q.arg(0, std::abs(diff), 10, kZero) + string
  27. : kDot + string.mid(diff);
  28. const auto begin = (result.constData());
  29. const auto end = (begin + result.size());
  30. auto ch = end - 1;
  31. auto zeroCount = 0;
  32. while (ch != begin) {
  33. if (((*ch) == kZero) && (zeroCount < kMaxChoppedZero)) {
  34. zeroCount++;
  35. } else {
  36. break;
  37. }
  38. ch--;
  39. }
  40. return result.chopped(zeroCount);
  41. }
  42. QString ToUsd(
  43. Data::EarnInt value,
  44. float64 rate,
  45. int afterFloat) {
  46. return ToUsd(StarsAmount(value), rate, afterFloat);
  47. }
  48. QString ToUsd(
  49. StarsAmount value,
  50. float64 rate,
  51. int afterFloat) {
  52. constexpr auto kApproximately = QChar(0x2248);
  53. const auto result = int64(base::SafeRound(value.value() * rate));
  54. return QString(kApproximately)
  55. + QChar('$')
  56. + MajorPart(result)
  57. + ((afterFloat > 0)
  58. ? MinorPart(result).left(afterFloat)
  59. : MinorPart(result));
  60. }
  61. } // namespace Info::ChannelEarn