summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorA. S. Budden <abudden@gmail.com>2016-05-31 13:26:41 +0100
committerA. S. Budden <abudden@gmail.com>2016-05-31 13:26:41 +0100
commit46a2993917edd73fe55623a06999f4811067a754 (patch)
tree1c8e4a53168de25a8317efb1447e09f3feae71ec /lib
parent0cc7c9a13ceb1afe703d328222dace69cf84a81b (diff)
downloadNim-46a2993917edd73fe55623a06999f4811067a754.tar.gz
Implemented function to split floating point numbers at the decimal place (equivalent to C's modf function). Fixes #4195.
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/math.nim25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim
index bd6764433..1edbfcab6 100644
--- a/lib/pure/math.nim
+++ b/lib/pure/math.nim
@@ -312,6 +312,23 @@ else:
       exponent = round(ex)
       result = x / pow(2.0, ex)
 
+proc splitDecimal*[T: float32|float64](x: T): tuple[intpart: T, floatpart: T] =
+  ## Breaks `x` into an integral and a fractional part.
+  ##
+  ## Returns a tuple containing intpart and floatpart representing
+  ## the integer part and the fractional part respectively.
+  ##
+  ## Both parts have the same sign as `x`.  Analogous to the `modf`
+  ## function in C.
+  var
+    absolute: T
+  absolute = abs(x)
+  result.intpart = floor(absolute)
+  result.floatpart = absolute - result.intpart
+  if x < 0:
+    result.intpart = -result.intpart
+    result.floatpart = -result.floatpart
+
 {.pop.}
 
 proc degToRad*[T: float32|float64](d: T): T {.inline.} =
@@ -399,3 +416,11 @@ when isMainModule:
     doAssert floatIsEqual(round(-547.652, -2), -500.0)
     doAssert floatIsEqual(round(-547.652, -3), -1000.0)
     doAssert floatIsEqual(round(-547.652, -4), 0.0)
+
+  block: # splitDecimal() tests
+    doAssert floatIsEqual(splitDecimal(54.674).intpart, 54.0)
+    doAssert floatIsEqual(splitDecimal(54.674).floatpart, 0.674)
+    doAssert floatIsEqual(splitDecimal(-693.4356).intpart, -693.0)
+    doAssert floatIsEqual(splitDecimal(-693.4356).floatpart, -0.4356)
+    doAssert floatIsEqual(splitDecimal(0.0).intpart, 0.0)
+    doAssert floatIsEqual(splitDecimal(0.0).floatpart, 0.0)