decimal formatting without rounding .net

后端 未结 3 1108
悲&欢浪女
悲&欢浪女 2021-01-25 07:06

Yesterday I asked this general question about decimals and their internal precisions. Here is a specific question about the scenario I\'m trying to address.

I have colu

相关标签:
3条回答
  • 2021-01-25 07:31

    To output your required format with n=3, you could use:

    number.ToString("0.000###")
    

    With n as a parameter, then you could build a custom string format:

    string format = "0." + new string('0', n) + new string('#', 6 - n);
    s = number.ToString(format);
    
    0 讨论(0)
  • 2021-01-25 07:32

    You should be able to do this by formatting the value as such:

    var str = num.ToString("#0.000#####");
    

    The number of 0s determines the minimum number of digits, and the number of 0s plus #s the maximum number of digits. I'm not sure if you actually want the maximum, but I believe this is the closest you'll get. You could of course just set it to an arbitrary (large) number.

    0 讨论(0)
  • 2021-01-25 07:54

    Anything you could do on the decimal itself wouldn't be enough for at least the following reason: you couldn't store in a decimal number itself that you want x leading/trailing zeroes to be printed as the value is converted to a string. The decimal data type in .NET is just a value type made up of 128bit, all dedicated to representing the number. No information about formatting when the number is printed is included, and the fact that it's a value type allows it to be quickly passed as an argument on the stack, which is also a relief for the GC.
    You could wrap decimal into some class, generate instances of that class in your DAL and return a collection of those if you need to do some number crunching later in the app and if that's not the case you could simply apply the "stringification" in your DAL and return a collection of strings.

    0 讨论(0)
提交回复
热议问题