From 2acd7804299299ab5d900453a8b5074da431eb6d Mon Sep 17 00:00:00 2001 From: Markus Quaritsch <markus.quaritsch@tugraz.at> Date: Mon, 27 Jun 2022 15:27:07 +0200 Subject: [PATCH] refactor 'toDouble' extension method and use tryParse --- .../VectoCommon/Utils/StringExtensionMethods.cs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/VectoCommon/VectoCommon/Utils/StringExtensionMethods.cs b/VectoCommon/VectoCommon/Utils/StringExtensionMethods.cs index c89db25926..6a91bd48ec 100644 --- a/VectoCommon/VectoCommon/Utils/StringExtensionMethods.cs +++ b/VectoCommon/VectoCommon/Utils/StringExtensionMethods.cs @@ -54,14 +54,17 @@ namespace TUGraz.VectoCommon.Utils throw new FormatException("Cannot convert an empty string to a number."); } - try { - return double.Parse(self, CultureInfo.InvariantCulture); - } catch (FormatException) { - if (defaultValue.HasValue) { - return defaultValue.Value; - } - throw; + var success = double.TryParse(self, out var retVal); + if (success) { + return retVal; + } + + if (defaultValue.HasValue) { + return defaultValue.Value; } + + // throws an exception + return double.Parse(self, CultureInfo.InvariantCulture); } public static int ToInt(this string self, int? defaultValue = null) -- GitLab