5

Requirement is to format a decimal number to a string, but with a maximum of 10 digits in total, for example:

  • 7846.05368740952 -> "7846.053687"
  • 47585.7350421593 -> "47585.73504"

Using {0:0.######} obviously doesn't work because it doesn't take into account the total number of digits... is there a formatting string that does this kind of formatting, or does it require extra code to achieve this?

EDIT: I'm trying to set a cell format with Aspose.Cells using the Custom property on the style of a cell. It seems that G10 doesn't work.

L-Four
  • 13,345
  • 9
  • 65
  • 109
  • Refer this http://stackoverflow.com/questions/11789194/string-format-how-can-i-format-to-x-digits-regardless-of-decimal-place – Irshad Nov 17 '15 at 09:59
  • Thank you, I saw that but it's quite some code. I need to format an excel cell with aspose cells using a format string, so I'm wondering whether it can be done without such logic. – L-Four Nov 17 '15 at 10:03
  • 1
    Note: For others finding this question if you're needing maximum number of digits *after* the decimal point then see this answer https://stackoverflow.com/questions/6951335/using-string-format-to-show-decimal-up-to-2-places-or-simple-integer – Simon_Weaver Oct 13 '17 at 18:44

1 Answers1

3

Probably, you're looking for "G10" format string

   Double s = 7846.05368740952; 
   // 7846.053687
   String result = s.ToString("G10");

this formatting works with Decimal as well:

   Decimal d = 47585.7350421593M;
   // 47585.73504
   String result = d.ToString("G10");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thank you. This works with string.Format, but form some reason not if I use it when setting a cell format with Aspose Cells like: var style = worksheet.Cells[1, 1].GetStyle(); style.Custom = "G10"; – L-Four Nov 17 '15 at 10:15
  • As far as I can see, *Aspose Cells* connects with *MS Excel* which has its own formats: https://support.office.com/en-ca/article/Create-or-delete-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4 – Dmitry Bychenko Nov 17 '15 at 10:23
  • Indeed. Well, in that case I guess I can use string.format before I set the value and the cell and not use the style. That works... Thanks! – L-Four Nov 17 '15 at 10:25
  • BTW, "G" format will give you scientific notation in some cases, so be warned. – Scott Smith May 23 '23 at 15:54