简体   繁体   English

如何在不替换小数的情况下将小数转换为字符串?

[英]How do I convert a decimal to a string without replacing decimals?

I have an object, CellData , that is equal to -0.000009482102880653542 . 我有一个对象CellData ,它等于-0.000009482102880653542

I want to display as is when exporting it as a .csv file. 将其导出为.csv文件时,我想按原样显示。 To do that I have to convert the object to a string. 为此,我必须将对象转换为字符串。

output = CellData.ToString();
output = string.Format("{0}", CellData);

The above two cases result in output being -9.48210288065354E-06 . 以上两种情况导致output-9.48210288065354E-06 I would like it to return output as -0.0000094821028806535423 (with decimals). 我希望它将output返回为-0.0000094821028806535423 (带小数)。

Is there anyway I can get this working? 无论如何,我可以使它正常工作吗?

If you store the number as a Decimal, it will output in non-scientific (normal) notation. 如果将数字存储为小数,它将以非科学(正常)表示法输出。 Depending on where the data is coming from, you may have to convert from double: 根据数据的来源,您可能需要从double转换:

double myNumber = -0.0000094821028806535423;
Object CellData = new Decimal(myNumber);

(gives -0.00000948210288065354), or you may be able to directly use a Decimal: (-0.00000948210288065354),或者您可以直接使用小数:

Object CellData = -0.0000094821028806535423m;

The result is less precise if you convert from double as a double cannot exactly represent all numbers, and the more calculations you perform on them the further they may end up from an exact result. 如果从double转换,则结果不太精确,因为double不能完全代表所有数字,并且对它们执行的计算越多,最终得到的精确结果就越多。

If the number originates in your code and you don't need to perform any calculations on it, you could also just store it as a string directly. 如果数字起源于您的代码,并且您不需要对其进行任何计算,则也可以直接将其存储为字符串。

Try without the 尝试不使用

output = string.Format("{0}", CellData);

Leave only the 只留下

output = CellData.ToString(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM