简体   繁体   中英

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

I have an object, CellData , that is equal to -0.000009482102880653542 .

I want to display as is when exporting it as a .csv file. 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 . I would like it to return output as -0.0000094821028806535423 (with decimals).

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 myNumber = -0.0000094821028806535423;
Object CellData = new Decimal(myNumber);

(gives -0.00000948210288065354), or you may be able to directly use a Decimal:

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.

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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