3

Possible Duplicate:
Leave only two decimal places after the dot
Formatting a float to 2 decimal places

If I have a float that consists of something like 153.2154879, is there any way to convert it to string but only show 4 decimal places? I know I can format it using "000.000", but the front number doesnt always have to be 3 digits. So is there a way to show all the front numbers (153), but only the first 4 characters after the point in a string?

Community
  • 1
  • 1
TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101

3 Answers3

8

Something like this should do:

your_number.ToString("0.####");

This will show a max of 4 decimal places.

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • `your_number.ToString("0.####")` would be more efficient, as well as offering culture-sensitive overloads. – phoog Apr 17 '12 at 18:22
  • -1. Converting a float to string and then back to float just to **round it** makes no sense. – Aliostad Apr 17 '12 at 18:28
  • @Aliostad rounding and truncating are 2 different things. Formatting a number 2 a max of 4 decimal places is not rounding. I updated my answer to include a more "efficient approach" as suggested by phoog. – Icarus Apr 17 '12 at 18:40
7

I usually use a format string like "#0.0000".

Justin
  • 6,611
  • 3
  • 36
  • 57
5

You can use the C# function Math.Round function.

float a= 153.213456; Math.Round(a,3); this would round up the number to 153.213 then get convert it to string.

Lukasz Bator
  • 121
  • 5
  • The string formatting code is going to round the number again; there's no reason to call Math.Round first. – phoog Apr 17 '12 at 18:23
  • @phoog Do you mean you convert the float to string and then convert back to float and not use the Round which is designed for the float?? – Aliostad Apr 17 '12 at 18:27
  • @Aliostad of course not! The question is about *displaying* a float with a given number of decimal points, which means *converting it to a string* with that number of decimal points. I mean that *it is inefficient to use `Round` for the purpose of formatting a number for display.* If the requirement is to have a rounded `float` in IEEE single binary format, for storage or calculation, then of course you should use `Round`. – phoog Apr 17 '12 at 18:41
  • @phoog I think Aliostad confuses truncating with rounding. See his comment to my answer. – Icarus Apr 17 '12 at 18:42