美好的一天,我有一个使用Open XML上传excel文件的MVC应用程序。该文件具有我传递回teh视图的deciml值,但是当我将应用程序转发给teh服务器时,它返回带有前面小数位的值,例如292,28返回为292.27999999999997,而85,7703返回为85.770300000000006。我已尝试在代码中添加数字格式,但它似乎无法正常工作,请参阅下面的代码
在这里,我将我的Excel值映射到我的对象。
private static CleanSupplierClaim MappExcelOpenXMLtoGenericList(IList<string> rowData, IList<string> columnNames)
{
var cleanSupplierClaims = new CleanSupplierClaim()
{
Action = rowData[columnNames.IndexFor("Action")],
Line_Number = rowData[columnNames.IndexFor("Lineno")],
Total_Claim = rowData[columnNames.IndexFor("TotalClaim")].ToDecimalNullable(), //Convert.ToDecimal(Math.Round(Convert.ToDouble(rowData[columnNames.IndexFor("TotalClaim")].ToDoubleNullable()),2)),
Currency = rowData[columnNames.IndexFor("Currency")],
ClaimReference = rowData[columnNames.IndexFor("ClaimReference")]
};
return cleanSupplierClaims;
}
这里我获取单元格值并尝试格式化从文件中获得的十进制类型
private static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
var culture = new CultureInfo("en-us");
culture.NumberFormat.CurrencyDecimalDigits = 3;
if (cell == null) return null;
string value = cell.InnerText;
//Process values particularly for those data types.
if (cell.DataType != null)
{
switch (cell.DataType.Value)
{
//Obtain values from shared string table.
case CellValues.SharedString:
var sstPart = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
value = sstPart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText.Trim();
break;
//Optional boolean conversion.
case CellValues.Boolean:
var booleanToBit = ConfigurationManager.AppSettings["BooleanToBit"];
if (booleanToBit != "Y")
{
value = value == "0" ? "FALSE" : "TRUE";
}
break;
//specifire = "F";
case CellValues.Number:
return Convert.ToDecimal(cell.CellValue.Text).ToString(culture);
default:
if (cell.CellValue != null)
return cell.CellValue.Text;
return string.Empty;
}
}
return value;
}
我在我的sql数据库中将十进制字段设置为3的小数位,但它仍然返回不正确的十进制值,格式不正确。
关于如何解决这个问题的任何想法,亲切的问候
答案 0 :(得分:0)
希望这有帮助:
string stringNumber = "0.1230000";
decimal decimalNumber = decimal.Parse(stringNumber, CultureInfo.InvariantCulture);//or another culture
decimal roundedNuber = decimal.Round(decimalNumber, 3);