What is the best datatype for holding percent values ranging from 0.00% to 100.00%?
decimal(p,s) / float(n) / real – Are used to store decimal numbers. We can expect that most numerical values we want to store are actually decimal values – percentage, graphical coordinates, sports results etc. bit – Uses only 1 bit to store value 0 or 1 (NULL if not defined).
You should use decimal(p,s) in 99.9% of cases. Percent is only a presentation concept: 10% is still 0.1. Simply choose precision and scale for the highest expected values/desired decimal places when expressed as real numbers. You can have p = s for values < 100% and simply decide based on decimal places.
Finding Percentage using Two Variables You have to rely on basic arithmetic operations i.e. (number1/number2 x 100) to find percentages in SQL Server.
The percent ("P") format specifier is used to multiply a number by 100. It converts the number into a string representing a % (percentage). In the same way, using (“P1”), would only include a single vale after decimal-point.
Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages:
decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor).decimal(5,2) with an appropriate CHECK constraint.Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.
decimal.columnName decimal(precision, scale). Precision says the total number of digits that can be held in the number, scale says how many of those are after the decimal place, so decimal(3,2) is a number which can be represented as #.##; decimal(5,3) would be ##.###. decimal and numeric are essentially the same thing. However decimal is ANSI compliant, so always use that unless told otherwise (e.g. by your company's coding standards).Example Scenarios
decimal(5,4).decimal(3,2).Example:
if object_id('Demo') is null create table Demo ( Id bigint not null identity(1,1) constraint pk_Demo primary key , Name nvarchar(256) not null constraint uk_Demo unique , SomePercentValue decimal(3,2) constraint chk_Demo_SomePercentValue check (SomePercentValue between 0 and 1) , SomePrecisionPercentValue decimal(5,2) constraint chk_Demo_SomePrecisionPercentValue check (SomePrecisionPercentValue between 0 and 1) ) Further Reading:
0 to 1 vs 0 to 100: C#: Storing percentages, 50 or 0.50? If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With