LocaleHelper.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * LocaleHelper.h - compatibility functions for handling decimal separators
  3. * Providing helper functions which handle both periods and commas
  4. * for decimal separators to load old projects correctly
  5. *
  6. * Copyright (c) 2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  7. * Copyright (c) 2018 Hyunjin Song <tteu.ingog/at/gmail.com>
  8. *
  9. * This file is part of LMMS - https://lmms.io
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2 of the License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public
  22. * License along with this program (see COPYING); if not, write to the
  23. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  24. * Boston, MA 02110-1301 USA.
  25. *
  26. */
  27. #ifndef LOCALEHELPER_H
  28. #define LOCALEHELPER_H
  29. #include <QLocale>
  30. #include <limits>
  31. #include <cmath>
  32. namespace LocaleHelper
  33. {
  34. inline double toDouble(QString str, bool* ok = nullptr)
  35. {
  36. bool isOkay;
  37. double value;
  38. QLocale c(QLocale::C);
  39. c.setNumberOptions(QLocale::RejectGroupSeparator);
  40. value = c.toDouble(str, &isOkay);
  41. if (!isOkay)
  42. {
  43. QLocale german(QLocale::German);
  44. german.setNumberOptions(QLocale::RejectGroupSeparator);
  45. value = german.toDouble(str, &isOkay);
  46. }
  47. if (ok != nullptr) {*ok = isOkay;}
  48. return value;
  49. }
  50. inline float toFloat(QString str, bool* ok = nullptr)
  51. {
  52. double d = toDouble(str, ok);
  53. if (!std::isinf(d) && std::fabs(d) > std::numeric_limits<float>::max())
  54. {
  55. if (ok != nullptr) {*ok = false;}
  56. return 0.0f;
  57. }
  58. return static_cast<float>(d);
  59. }
  60. }
  61. #endif // LOCALEHELPER_H