tfloat4.nim 2.0 KB

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