Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
405
Round decimals using "to even" instead of "away from zero"
posted

Hi,

It is very easy to format your decimal values in the grid to for instance 4 decimals using the format string "N4".
"Unfortunately" this way to format always use "away from zero" rounding (that's the way the .NET formatting works).
I would like to change this to "to even" rounding instead.

First I tried to write my own IFormatProvider and set the column property FormatInfo to my formatting class.
This doesn't seem to be possible however (after some investigations in .NET Reflector). The way the UltraGrid
formats strings ((decimal)dataValue).ToString(this.format, this.formatInfo), the .NET framework only accepts
NumberFormatInfo (which I can't inherit from) or uninherited CultureInfo as formatProvider.
(If the UltraGrid had used String.Format(this.formatInfo, this.format, (decimal)dataValue) I guess it had
worked to use your own IFormatProvider.)

I hope I'm wrong cause this would be a nice way to solve it.

My second approach was to create a DataFilter to affect the way the decimal value is displayed. I'm adding
my conversion logic in the convert "ConversionDirection.EditorToDisplay"-direction.
This works, BUT when I put the cell in edit mode it still shows my formatted value. I want it to behave like
when setting the format property, i.e. the "real" value is displayed when I go into edit mode.
How do I achieve this?

Best Regards
-tomas.

"to even": means that 1.22225 is rounded to 1.2222
"away from zero": means that 1.22225 is rounded to 1.2223

 

 


 

Parents
  • 469350
    Offline posted

    Hi tomas,

    I'm not sure what you mean about a NumberFormatInfo. I don't see that anywhere. 

    I was able to get this to work like so: 

    public class MyFormatProvider : IFormatProvider
        {
            #region IFormatProvider Members

            public object GetFormat(Type formatType)
            {
                if (formatType == typeof(ICustomFormatter))
                    return new MyCustomFormatter();

                throw new NotSupportedException();
            }

            #endregion
        }

        public class MyCustomFormatter : ICustomFormatter
        {
            #region ICustomFormatter Members

            public string Format(string format, object arg, IFormatProvider formatProvider)
            {
                decimal argDecimal = (decimal)arg;
                return (Math.Round(argDecimal, 2, MidpointRounding.ToEven)).ToString();
            }

            #endregion
        }

Reply Children