custom format for decimal c#

不打扰是莪最后的温柔 提交于 2019-12-10 18:05:33

问题


I'm trying to format a decimal value with decimals to a custom format without comas or points , Having checking http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx but can't find the format I need

I need to convert a decimal value for example 3.1416 to 314 or even better 0000000314, any clue?


回答1:


To scale by 100 and show up to 9 leading zeros use

String.Format("{0:0000000000}", (value * 100));



回答2:


For just display

String.Format("{0:##########}", (value * 100))



回答3:


Make a simple Method

   public static string FormatNumberMultipliedByOneHundred(string inputString)
   {
       inputString = string.Format("{0:########}", (inputString * 100));
       return inputString;
   }



回答4:


I guess the best way to solve this issue is using ValueConverters. With a few easy steps you can write an ValueConverter that takes an arbitrary object as input applies some conversion and outputs the result.

These ValueConverters are highly efficient and in case you write one converter for one particular conversion (take care of high cohesion) they are very handy and re-usable

What you need is the IValueConverter interafce which you must implement in your Converter class. A conversion always converts some A to some B. So the interface contains exactly two methods that are responsible for converting in one direction and for converting back (the opposite direction)

It's good practice to write a general base class that all your converters can inherit:

public class ValueConverterBase : IValueConverter {

public virtual object Convert (object value, Type convertTargetType, object convertParameter, System.Globalization.CultureInfo convertCulture) {

        return value;
    }

    public virtual object ConvertBack (object value, Type convertBackTargetType, object convertBackParameter, System.Globalization.CultureInfo convertBackCulture) {

        return value;
    }

}

Then you can write your converter classes that actually implement the conversion code:

public class NumberConverter : ValueConverterBase {

    public override object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {

        // code for converting
    }

    public override object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {

        // code for converting back
    }

}

You can find plenty of documentation and tutorials on ValueConverter on the internet.

Hope this helps :)



来源:https://stackoverflow.com/questions/8839040/custom-format-for-decimal-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!