From 45c15f887ee85c51a03eace0e2c01bb08dc6f129 Mon Sep 17 00:00:00 2001 From: Taylor Buchanan Date: Thu, 11 Oct 2018 08:34:37 -0500 Subject: [PATCH] Fix General format of large numbers for AutoSizeColumn --- src/NPOI/SS/UserModel/DataFormatter.cs | 4 ++-- src/NPOI/SS/Util/Format.cs | 30 ++++++++++++++++---------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/NPOI/SS/UserModel/DataFormatter.cs b/src/NPOI/SS/UserModel/DataFormatter.cs index 379e903..97d7724 100644 --- a/src/NPOI/SS/UserModel/DataFormatter.cs +++ b/src/NPOI/SS/UserModel/DataFormatter.cs @@ -118,10 +118,10 @@ namespace NPOI.SS.UserModel invalidDateTimeString = buf.ToString(); } /** General FormatBase for whole numbers. */ - private static DecimalFormat generalWholeNumFormat = new DecimalFormat("0"); + private static DecimalFormat generalWholeNumFormat = new DecimalFormat("0", true); /** General FormatBase for decimal numbers. */ - private static DecimalFormat generalDecimalNumFormat = new DecimalFormat("#.##########"); + private static DecimalFormat generalDecimalNumFormat = new DecimalFormat("#.##########", true); /** A default FormatBase to use when a number pattern cannot be Parsed. */ private FormatBase defaultNumFormat; diff --git a/src/NPOI/SS/Util/Format.cs b/src/NPOI/SS/Util/Format.cs index 24c0445..21c7065 100644 --- a/src/NPOI/SS/Util/Format.cs +++ b/src/NPOI/SS/Util/Format.cs @@ -173,12 +173,20 @@ namespace NPOI.SS.Util private string pattern; + private bool isGeneral; + public DecimalFormat(string pattern) { if (pattern.IndexOf("'", StringComparison.Ordinal) != -1) throw new ArgumentException("invalid pattern"); this.pattern = pattern; } + + internal DecimalFormat(string pattern, bool isGeneral) : this(pattern) + { + this.isGeneral = isGeneral; + } + public string Pattern { get @@ -194,19 +202,19 @@ namespace NPOI.SS.Util } public override string Format(object obj, CultureInfo culture) { - //invalide fraction + // Invalid fraction pattern = RegexFraction.Replace(pattern, "/"); - + double n = Convert.ToDouble(obj, CultureInfo.InvariantCulture); + if (pattern.IndexOf("'", StringComparison.Ordinal) != -1) - { - //return ((double)obj).ToString(); - return Convert.ToDouble(obj, CultureInfo.InvariantCulture).ToString(culture); - } - else - { - return Convert.ToDouble(obj, CultureInfo.InvariantCulture).ToString(pattern, culture); - //return ((double)obj).ToString(pattern) ; - } + return n.ToString(culture); + + // Excel displays in scientific notation if the cell form is General and there are 12 or more digits + // https://support.office.com/en-us/article/display-numbers-in-scientific-exponential-notation-f85a96c0-18a1-4249-81c3-e934cd2aae25 + if (isGeneral && Math.Floor(Math.Log10(n) + 1) >= 12) + pattern = "E4"; + + return n.ToString(pattern, culture); } public override StringBuilder Format(object obj, StringBuilder toAppendTo, CultureInfo culture)