Challenge
Given a number x
and a number n
, round number x
to n
significant figures and output the result.
Significant figures
The significant figures of a number are digits that carry meaning contributing to its measurement resolution. This includes all numbers except leading zeroes.
Bear in mind that leading zeroes after a decimal point are still insignificant figures.
When rounding a digit, you must round away from zero if the following digit is greater or equal than five.
All trailing zeroes after a decimal point are counted as significant.
Input
The first number will be x
, the number to be rounded. The second number will be n
, the number of significant figures you should round x
to.
x
will be a number (your code should handle both integers and floating points) between -1,000,000,000 and 1,000, 000,000 inclusive. n
will be a positive integer between 1 and 50 inclusive. n
will never be greater than the nunber of digits in x
.
The input will never be 0
or any form of 0
, e.g. 0.000
or 000
.
Examples
Inputs: 2.6754, 2
Output: 2.7
An output of 2.7000
would be invalid because the trailing zeroes after the decimal point are counted as significant figures.
Inputs: 0.00034551, 4
Output: 0.0003455
Inputs: 50237.1238, 3
Output: 50200
Note that this must not have a decimal point.
Inputs: 2374905, 1
Output: 2000000
Inputs: 543.0489, 4
Output: 543.0
Inputs: 15, 1
Output: 20
Inputs: 520.3, 3
Output: 520
If you wish, you can output 520.
instead but not 520.0
.
Inputs: -53.87, 2
Output: -54
Inputs: 0.0999, 2
Output: 0.10
Rules
Built-in functions and libraries which allow you to round a number to n
significant figures are disallowed.
Winning
The shortest code in bytes wins.
Inputs: 520.3, 3
, isn't the decimal point in the answer520.
crucial? \$\endgroup\$2.0 x 10^2
, showing the 2 sigfigs. \$\endgroup\$