How can I override the currency formatting for the current culture for an ASP.NET web application?

后端 未结 2 1153
猫巷女王i
猫巷女王i 2021-01-20 10:15

The currency decimal and thousand separators for the en-ZA region are \',\' and \' \' respectively, but the separators in common use are \'.\' for decimal, plus my user want

2条回答
  •  醉话见心
    2021-01-20 10:57

    Having asked many questions and done many experiments, I have decided that it's safe to state that the only way of doing this is to use controls derived from the out of box controls and do your own formatting using a customised culture object. Derive your control from e.g. BoundField and provide your own FormatProvider:

    public class BoundReportField : BoundField
    {
        protected virtual string GetDefaultFormatString(FieldFormatTypes formatType)
        {
            var prop = typeof(FormatStrings).GetProperty(formatType.ToString()).GetValue(null, null);
            return prop.ToString();
        }
    
        protected virtual IFormatProvider GetFormatProvider(FieldFormatTypes formatType)
        {
            var info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            info.NumberFormat.CurrencyDecimalDigits = 0;
            info.NumberFormat.CurrencySymbol = "R";
            info.NumberFormat.CurrencyGroupSeparator = ",";
            info.NumberFormat.CurrencyDecimalSeparator = ".";
            return info;
        }
    
        private FieldFormatTypes _formatType;
        public virtual FieldFormatTypes FormatType
        {
            get { return _formatType; }
            set
            {
                _formatType = value;
                DataFormatString = GetDefaultFormatString(value);
            }
        }
    
        protected override string FormatDataValue(object dataValue, bool encode)
        {
            // TODO Consider the encode flag.
            var formatString = DataFormatString;
            var formatProvider = GetFormatProvider(_formatType);
            if (string.IsNullOrWhiteSpace(formatString))
            {
                formatString = GetDefaultFormatString(_formatType);
            }
            return string.Format(formatProvider, formatString, dataValue);
        }
    }
    

    I will publish an article later with all the gory details.

提交回复
热议问题