tfloat4.nim 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. discard """
  2. file: "tfloat4.nim"
  3. output: "passed all tests."
  4. exitcode: 0
  5. """
  6. import math, strutils
  7. proc c_sprintf(buf, fmt: cstring) {.importc:"sprintf", header: "<stdio.h>", varargs.}
  8. proc floatToStr(f: float64): string =
  9. var buffer: array[128, char]
  10. c_sprintf(addr buffer, "%.16e", f)
  11. result = ""
  12. for ch in buffer:
  13. if ch == '\0':
  14. return
  15. add(result, ch)
  16. let testFloats = [
  17. "0", "-0", "0.", "0.0", "-0.", "-0.0", "-1", "1", "1.", ".3", "3.3", "-.3", "-99.99",
  18. "1.1e10", "-2e100", "1.234e-10", "1.234e+10",
  19. "-inf", "inf", "+inf",
  20. "3.14159265358979323846264338327950288",
  21. "1.57079632679489661923132169163975144",
  22. "0.785398163397448309615660845819875721",
  23. "1.41421356237309504880168872420969808",
  24. "0.707106781186547524400844362104849039",
  25. "2.71828182845904523536028747135266250",
  26. "0.00097656250000000021684043449710088680149056017398834228515625"
  27. ]
  28. when not defined(windows):
  29. # Windows' sprintf produces niceties like -1.#INF...
  30. for num in testFloats:
  31. doAssert num.parseFloat.floatToStr.parseFloat == num.parseFloat
  32. doAssert "0".parseFloat == 0.0
  33. doAssert "-.1".parseFloat == -0.1
  34. doAssert "2.5e1".parseFloat == 25.0
  35. doAssert "1e10".parseFloat == 10_000_000_000.0
  36. doAssert "0.000_005".parseFloat == 5.000_000e-6
  37. doAssert "1.234_567e+2".parseFloat == 123.4567
  38. doAssert "1e1_00".parseFloat == "1e100".parseFloat
  39. doAssert "3.1415926535897932384626433".parseFloat ==
  40. 3.1415926535897932384626433
  41. doAssert "2.71828182845904523536028747".parseFloat ==
  42. 2.71828182845904523536028747
  43. doAssert 0.00097656250000000021684043449710088680149056017398834228515625 ==
  44. "0.00097656250000000021684043449710088680149056017398834228515625".parseFloat
  45. echo("passed all tests.")