From 8ab002b7852cd73235ca3c017a457c15d00b193d Mon Sep 17 00:00:00 2001 From: bfisch Date: Tue, 16 Feb 2021 21:40:53 -0800 Subject: [PATCH] Fixing issue when Fraction is >= int.MaxValue Fixing issue when an excel cell is formatted as "Fraction" and the value is greater than int.MaxValue (2,147,483,647). Prior to this fix, a value greater than int.MaxValue throws the error "System.OverflowException: Negating the minimum value of a twos complement number is invalid." --- src/ExcelNumberFormat/ExcelNumberFormat.csproj | 2 +- src/ExcelNumberFormat/Formatter.cs | 4 ++-- test/ExcelNumberFormat.Tests/Class1.cs | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/ExcelNumberFormat/ExcelNumberFormat.csproj b/src/ExcelNumberFormat/ExcelNumberFormat.csproj index 86713e7..ffe7f7f 100644 --- a/src/ExcelNumberFormat/ExcelNumberFormat.csproj +++ b/src/ExcelNumberFormat/ExcelNumberFormat.csproj @@ -2,7 +2,7 @@ net20;netstandard1.0;netstandard2.0 - 1.1.0 + 1.1.1 true true .NET library to parse ECMA-376 number format strings and format values like Excel and other spreadsheet softwares. diff --git a/src/ExcelNumberFormat/Formatter.cs b/src/ExcelNumberFormat/Formatter.cs index c7c3136..4481451 100644 --- a/src/ExcelNumberFormat/Formatter.cs +++ b/src/ExcelNumberFormat/Formatter.cs @@ -528,14 +528,14 @@ static string FormatExponential(double value, Section format, CultureInfo cultur static string FormatFraction(double value, Section format, CultureInfo culture) { - int integral = 0; + long integral = 0; int numerator, denominator; bool sign = value < 0; if (format.Fraction.IntegerPart != null) { - integral = (int)Math.Truncate(value); + integral = (long)Math.Truncate(value); value = Math.Abs(value - integral); } diff --git a/test/ExcelNumberFormat.Tests/Class1.cs b/test/ExcelNumberFormat.Tests/Class1.cs index e0f21aa..9015a5f 100644 --- a/test/ExcelNumberFormat.Tests/Class1.cs +++ b/test/ExcelNumberFormat.Tests/Class1.cs @@ -327,6 +327,8 @@ public void TestFraction() Test(0, "0", "0"); + Test((double)int.MaxValue, "# ?/?", $"{int.MaxValue} "); + Test((double)int.MaxValue + 1, "# ?/?", $"{(long)int.MaxValue + 1} "); } void TestExponents(double value, string expected1, string expected2, string expected3, string expected4)