From 5ae3fb2c3804a74251c359d603e00bd947aaea15 Mon Sep 17 00:00:00 2001 From: Silvan Mosberger Date: Sat, 7 Mar 2020 02:44:56 +0100 Subject: lib/strings: Add floatToString --- lib/strings.nix | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'lib/strings.nix') diff --git a/lib/strings.nix b/lib/strings.nix index 74e3eaa0722de..0baa942355c0e 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" ] || -- cgit 1.4.1