I am working on a JavaScript function that takes two values: precision of a decimal value & scale of a decimal value.
This function should calculate the maximum value that can be stored in a decimal of that size.
For example: a decimal with a precision of 5 and a scale of 3 would have a maximum value of 99.999.
What I have does the job, but it’s not elegant. Can anyone think of something more clever?
Also, please forgive the use of this weird version of Hungarian notation.
JavaScript
x
28
28
1
function maxDecimalValue(pintPrecision, pintScale) {
2
/* the maximum integers for a decimal is equal to the precision - the scale.
3
The maximum number of decimal places is equal to the scale.
4
For example, a decimal(5,3) would have a max value of 99.999
5
*/
6
// There's got to be a more elegant way to do this...
7
var intMaxInts = (pintPrecision- pintScale);
8
var intMaxDecs = pintScale;
9
10
var intCount;
11
var strMaxValue = "";
12
13
// build the max number. Start with the integers.
14
if (intMaxInts == 0) strMaxValue = "0";
15
for (intCount = 1; intCount <= intMaxInts; intCount++) {
16
strMaxValue += "9";
17
}
18
19
// add the values in the decimal place
20
if (intMaxDecs > 0) {
21
strMaxValue += ".";
22
for (intCount = 1; intCount <= intMaxDecs; intCount++) {
23
strMaxValue += "9";
24
}
25
}
26
return parseFloat(strMaxValue);
27
}
28
Advertisement
Answer
Haven’t tested it:
JavaScript
1
4
1
function maxDecimalValue(precision, scale) {
2
return Math.pow(10,precision-scale) - Math.pow(10,-scale);
3
}
4
precision must be positive
JavaScript
1
5
1
maxDecimalValue(5,3) = 10^(5-3) - 10^-3 = 100 - 1/1000 = 99.999
2
maxDecimalValue(1,0) = 10^1 - 10^0 = 10 - 1 = 9
3
maxDecimalValue(1,-1) = 10^(1+1) - 10^1 = 100 - 10 = 90
4
maxDecimalValue(2,-3) = 10^(2+3) - 10^3 = 100000 - 1000 = 99000
5