String.Format 10.0000 to 10.00 but keep 10.0001

Hi,

I'm getting doubles with 4 decimal places, however when the last two digits are 00, I want to format to .00 but if the 3rd or 4th decimal place contains a value different to 0 I want to leave the 4 decimal places. Is there an easy way to do this with String.Format or would I have to evaluate the values and use the appropriate string formatter

Thanks,

Tom


Answer this question

String.Format 10.0000 to 10.00 but keep 10.0001

  • BTBL

    The default number of decimal places for InvariantInfo is 2. So you have to change it..
    See http://msdn2.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits.aspx

  • P Santosh

    Hello.

    or would I have to evaluate the values and use the appropriate string formatter
    Yes. You must evaluate C#: (v % 0.01) or VB: (v mod 0.01) for zero (or in fact close to zero, but never mind).

    Hope this helps.



  • IS dude

    well, but I don't want the default to be 4, default should be 2 UNLESS 3rd or 4th decimal place != 0

  • Rosh K Mathews

    nevermind, if(Math.Round(val, 2) != Math.Round(val, 4)) did the trick...

  • samsonknight

    OK, then you really need to determine what numbers are on the 3th and 4th place of your decimals and use appropriate IFormatProvider

  • Andy Larter

    hm, ok I haven't bothered with this for some time ..however I just tried this again:

    values % 0.01 gives me:

    26,91 = 0,00999999999999958
    26,8 = 1,52655665885959E-16
    26,79 = 0,00999999999999859
    -0,07 = -5,20417042793042E-18
    26,79 = 0,00999999999999859

    so how should I tell if it's a 2 or 4 decimal place value

  • AKS

    ok, will do then. I was just hoping that there might be an easy format string for this ;)

  • String.Format 10.0000 to 10.00 but keep 10.0001