views:

26

answers:

2

I'm reading excel and there's cell that represents total cost of budget in percents.

In excel it looks like 8%, but once i read it, i get string 8.33333333329E-2.

Got confused a bit.

What would be correct data type and parsing technique to use and avoid losing data?

+2  A: 

You probably have the excel cell formatting set to 0 decimal digits, and hence you see the wrong value, while 0.0833333333 is the actual value.

If you do want it as 0.08 (or 8%), round the value in excel.

leppie
Indeed. For background, percentages in Excel are actually floating point numbers, where 1.0 represents 100%, i.e. if you stick 0.25 in a cell in Excel and format it as a percentage, it'll display as "25%". This is why your 8.333E-2, roughly 0.08, displays at 8%, when formatted as a percentage with no decimal places.
Matt Gibson
No can do. Excel should not be touched at all.
Arnis L.
@Arnis L.: Excel is showing your eyes inaccurate data.
leppie
@leppie question is - how to work with it at .Net side now how it looks in excel. :)
Arnis L.
@Arnis L.: Convert it to string or round it, like the above answer, if that is what your really want to do.
leppie
@leppie it is string already. I want to save it in another data type that would represent percentage more naturally.
Arnis L.
+1  A: 

Something like ((int)Math.Round(value*100)).ToString() + "%";.

ChrisW
Arrggghhhhhh, please use the format specifier for strings, iow `value.ToString("P0")`. A lot shorter and less error-prone.
leppie
@leppi Are you saying you'd prefer to see `((int)Math.Round(value*100)).ToString("P0") + "%";`?
ChrisW
A good thing about Math.Round is that you control how it's rounded; for example, you can specify whether you want 0.077 to be displayed as 7% or as 8%.
ChrisW
@ChrisW: No, just `value.ToString("P0")`, it's all that is needed.
leppie
@ChrisW: If you use round like that, it is wrong. You have functions like floor, ceiling, truncate, etc for those. They also behave correctly on negative numbers.
leppie
`value` is string, i can't just multiple it with 100. Can't convert it to decimal cause of trailing `E-2`.
Arnis L.
@Arnis L.: `double.Parse` should have no issue parsing that.
leppie
Emm. It almost works. Period makes problems. `8.333...` fails, `8,333` works. What format provider it needs? Or anything else?
Arnis L.
@Arnis L. - My guess would be `NumberFormatInfo.InvariantInfo`
ChrisW
I guess it's fine now. Know how to parse it and know how to display it. Thank You ChrisW and leppie.
Arnis L.