/// <summary> /// 科學計數法值轉換成正常值 /// </summary> /// <param name="value"></param> /// <returns></returns> private object ValueScientificNotationConvert(JToken value) { if (value == null) return 0; string strData = ""; if (value.Type == JTokenType.String) { strData = value.ToString(); } else { strData = value.ToString(Formatting.Indented); } Decimal dData = 0.0M; try { if (strData.ToUpper().Contains("E")) { System.Globalization.NumberStyles sty = System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowDecimalPoint; try { dData = Decimal.Parse(strData, sty); } catch (Exception ex) { //轉換成decimal溢出時,轉換成字符串 if (ex is OverflowException) return ValueScientificNotationConvert1(value); } } else { if (!decimal.TryParse(strData, out dData)) return null; } } catch (Exception ex) { throw ex; } return dData; }
/// <summary> /// 科學計數法值轉換成正常值字符串 /// </summary> /// <param name="value"></param> /// <returns></returns> public string ValueScientificNotationConvert1(JToken value) { if (value == null) return ""; string s = ""; if (value.Type == JTokenType.String) { s = value.ToString(); } else { s = value.ToString(Formatting.Indented); } string num = String.Empty; string[] arr = s.Split('E'); bool isPart1Double = double.TryParse(arr[0], out var part1); int decimalDigitCountInPart1 = arr[0].IndexOf('.') == -1 ? 0 : arr[0].Length - 1 - arr[0].IndexOf('.'); string newPart2 = arr.ElementAtOrDefault(1); bool isPart2Int = int.TryParse(newPart2, out var part2); if (arr.Length == 1) { if (isPart1Double) num = part1.ToString(); } if (arr.Length == 2) { if (part2 < 0 || part2 - decimalDigitCountInPart1 < 0) { if (isPart1Double && isPart2Int) num = Decimal.Parse((part1 * Math.Pow(10, part2)).ToString(), System.Globalization.NumberStyles.Float).ToString(); // 此時Math.Pow(10, part2)並不會越界,故可以使用Decimal.Parse從scientific num轉換爲real num } else if (part2 - decimalDigitCountInPart1 >= 0) { num = part1.ToString().Replace(".", "") + new String('0', part2 - decimalDigitCountInPart1 + 1); // 避免越界,此處使用字符串拼接代替Math.Pow(10, part2),拼接還可用StringBuilder的append方法 } } return num; }