简体   繁体   中英

How can I round a Decimal value upto a precision so that the total number of digits doesnot cross 15?

I need to round values like 25979.699999999997 to 15 digits so it becomes 25979.7 and does not contain any insignificant zeroes.

Background: I am trying to parse an excel file using OpenXML SDK, and there a decimal value such as 25979.7 is read as 25979.699999999997.

When MS excel shows the value, it always rounds them to 15 digits and removes trailing zeroes so it becomes 25979.7, but when I am reading using OpenXML SDK it does not do that automatically.

Any idea?

EDIT: Actually I don't want to modify the value, just want to display in that format(as a string).

Well, you can try not so complicated math:

var x = 25979.699999999997;
var y = Math.Round(x, 15 - (int)Math.Floor(Math.Log10(x) + 1));

y will be exactly 25979.7

Here we calculating number of digits before decimal separator as

Math.Floor(Math.Log10(x) + 1)

and subtracting it from 15 gives us remaining fractional digits to round to.

Simply format your (umodified) value to get a nicly formated string:

double val = double.Parse("25979.699999999997");
string formatted = val.ToString("g");

The g formatting will do all the work for you.

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