Pure Programmer
Blue Matrix


Cluster Map

Project: Significant Digits

Write a function that rounds a floating point value to a specified number of significant digits. Significant digits are the the number of digits (omiting any leading zeros) that are actually known in a measured value. Use the math constants for π and the natural logarithm base, 𝑒, for your tests. Loop from 1 to 16 significant digits testing each value. Assert a precondition on the function to validate the proper range of 1-16 on the significant digits argument.

The roundSigDig() function should take the floating point value to round and the number of significant digits to keep (precision). It should return a new floating point value rounded to the number of significant digits. For example 1234 rounded to two significant digits is 1200 This rounding can be accomplished by multiplying the value (n) by 10int(precision-log10(n)-1), adding 0.5, computing the integer floor, then dividing by 10int(precision-log10(n)-1) again.

See [[Significant Figures]]

Output
$ node SignificantDigits.js π to 1 significant digits: 3.0000000000000000 π to 2 significant digits: 3.1000000000000001 π to 3 significant digits: 3.1400000000000001 π to 4 significant digits: 3.1419999999999999 π to 5 significant digits: 3.1415999999999999 π to 6 significant digits: 3.1415899999999999 π to 7 significant digits: 3.1415929999999999 π to 8 significant digits: 3.1415926999999999 π to 9 significant digits: 3.1415926500000002 π to 10 significant digits: 3.1415926540000001 π to 11 significant digits: 3.1415926536000001 π to 12 significant digits: 3.1415926535900001 π to 13 significant digits: 3.1415926535900001 π to 14 significant digits: 3.1415926535898002 π to 15 significant digits: 3.1415926535897900 π to 16 significant digits: 3.1415926535897931 ℯ to 1 significant digits: 3.0000000000000000 ℯ to 2 significant digits: 2.7000000000000002 ℯ to 3 significant digits: 2.7200000000000002 ℯ to 4 significant digits: 2.7180000000000000 ℯ to 5 significant digits: 2.7183000000000002 ℯ to 6 significant digits: 2.7182800000000000 ℯ to 7 significant digits: 2.7182819999999999 ℯ to 8 significant digits: 2.7182818000000002 ℯ to 9 significant digits: 2.7182818300000000 ℯ to 10 significant digits: 2.7182818279999998 ℯ to 11 significant digits: 2.7182818284999999 ℯ to 12 significant digits: 2.7182818284599999 ℯ to 13 significant digits: 2.7182818284589998 ℯ to 14 significant digits: 2.7182818284589998 ℯ to 15 significant digits: 2.7182818284590500 ℯ to 16 significant digits: 2.7182818284590451

Solution