summary refs log tree commit diff
path: root/lib
diff options
context:
space:
mode:
authorSilvan Mosberger <contact@infinisil.com>2020-03-07 02:44:56 +0100
committerSilvan Mosberger <contact@infinisil.com>2020-07-25 21:43:09 +0200
commit5ae3fb2c3804a74251c359d603e00bd947aaea15 (patch)
tree316b5386d4b649d0d6558de5b742f3054479d44a /lib
parentf1bc04254b98c0e2b9c1f232a2be9b5a41f71efb (diff)
downloadnixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar.gz
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar.bz2
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar.lz
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar.xz
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.tar.zst
nixpkgs-5ae3fb2c3804a74251c359d603e00bd947aaea15.zip
lib/strings: Add floatToString
Diffstat (limited to 'lib')
-rw-r--r--lib/strings.nix16
1 files changed, 16 insertions, 0 deletions
diff --git a/lib/strings.nix b/lib/strings.nix
index 74e3eaa0722..0baa942355c 100644
--- a/lib/strings.nix
+++ b/lib/strings.nix
@@ -612,6 +612,22 @@ rec {
   */
   fixedWidthNumber = width: n: fixedWidthString width "0" (toString n);
 
+  /* Convert a float to a string, but emit a warning when precision is lost
+     during the conversion
+
+     Example:
+       floatToString 0.000001
+       => "0.000001"
+       floatToString 0.0000001
+       => trace: warning: Imprecise conversion from float to string 0.000000
+          "0.000000"
+  */
+  floatToString = float: let
+    result = toString float;
+    precise = float == builtins.fromJSON result;
+  in if precise then result
+    else lib.warn "Imprecise conversion from float to string ${result}" result;
+
   /* Check whether a value can be coerced to a string */
   isCoercibleToString = x:
     builtins.elem (builtins.typeOf x) [ "path" "string" "null" "int" "float" "bool" ] ||