rounding-mode.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* Handle floating-point rounding mode within libc.
  2. Copyright (C) 2012-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #ifndef _ROUNDING_MODE_H
  16. #define _ROUNDING_MODE_H 1
  17. #include <fenv.h>
  18. #include <stdbool.h>
  19. #include <stdlib.h>
  20. /* Get the architecture-specific definition of how to determine the
  21. rounding mode in libc. This header must also define the FE_*
  22. macros for any standard rounding modes the architecture does not
  23. have in <fenv.h>, to arbitrary distinct values. */
  24. #include <get-rounding-mode.h>
  25. /* Return true if a number should be rounded away from zero in
  26. rounding mode MODE, false otherwise. NEGATIVE is true if the
  27. number is negative, false otherwise. LAST_DIGIT_ODD is true if the
  28. last digit of the truncated value (last bit for binary) is odd,
  29. false otherwise. HALF_BIT is true if the number is at least half
  30. way from the truncated value to the next value with the
  31. least-significant digit in the same place, false otherwise.
  32. MORE_BITS is true if the number is not exactly equal to the
  33. truncated value or the half-way value, false otherwise. */
  34. static bool
  35. round_away (bool negative, bool last_digit_odd, bool half_bit, bool more_bits,
  36. int mode)
  37. {
  38. switch (mode)
  39. {
  40. case FE_DOWNWARD:
  41. return negative && (half_bit || more_bits);
  42. case FE_TONEAREST:
  43. return half_bit && (last_digit_odd || more_bits);
  44. case FE_TOWARDZERO:
  45. return false;
  46. case FE_UPWARD:
  47. return !negative && (half_bit || more_bits);
  48. default:
  49. abort ();
  50. }
  51. }
  52. #endif /* rounding-mode.h */