C#: Storing percentages, 50 or 0.50?

后端 未结 5 1043
情书的邮戳
情书的邮戳 2021-02-19 10:53

When holding percentage values in variables is there a preference between holding them as whole numbers vs fractions. That is should the variable hold numbers between 0 and 100

相关标签:
5条回答
  • 2021-02-19 11:22

    I would be inclined to store them as 0 to 1, then there is no conversion required when using the number in a calculation.

    Using a number between 0 and 100 is more of a display / readability way of looking at the number. When you are displaying the percentage you can use String.Format("{0:P},percentage) which will expect the number to be between 0 and 1 but will display as 0 to 100.

    0 讨论(0)
  • 2021-02-19 11:26

    If you are using floating point fields (float, decimal, double), then 50.0 and 0.50 will have the same degree of precision. So, from this point, I would make decisions based on what similar fields in similar tables do, to give a sense of design unity.

    0 讨论(0)
  • 2021-02-19 11:27

    You can use doubles to represent both percentages and 0-1. But if you choose to store percentage as "whole number" I would advise against using integers, which would limit you if you ever want to represent 12.3%, for example.

    0 讨论(0)
  • 2021-02-19 11:31

    If you are doing a lot of math with fractions, you want to store the numerator and denominator separately as whole numbers. When using fractions to represent repeating or non-repeating decimals you can get rounding errors that grow the more operations you have.

    If you are just storing and presenting the number, then it really doesn't matter.

    What math do you plan to do with this number, if any?

    0 讨论(0)
  • 2021-02-19 11:40

    I think this is trivial... both are the same

    I mean in terms of calculations/displaying info...

    00.50 is cool for calculations
    
    50.00 is cool for displaying
    
    0 讨论(0)
提交回复
热议问题