Manual:Rounding numbers
In MediaWiki, rounding up a number can come in different forms.
Using #expr and #ifexpr
[edit]#expr
[edit]In a parser function, the #expr
and #ifexpr
operators are one of the ways to perform rounding calculations. In the expression, they round the number on the left to the nearest multiple of 10 raised to the value of the power on the right.
Where a power with a negative value, for example, -2
, is the "Hundreds" -3
, is the "Thousands", etc. They begin before a decimal point.
Then a power with a positive value, for example, 2
, is the "Hundredth", 3
, is the "Thousandth", etc. They begin after a decimal point.
0
is the "ones".
For example:
{{#expr: 123.456 round 0}}
→ 123{{#expr: 123.456 round -1}}
→ 120{{#expr: 123.456 round 2}}
→ 123.46
Attempting to round a very large number to fine precision can result in infinity (INF). This happens because the process involves dividing a very large number by a very small one, leading to an overflow. Hence, the original value without the infinity is given as the answer.
For example:
{{#expr: 1e -92 round 400}}
→ 1.0E-92{{#expr: 1e 209 round 100}}
→ 1.0E+209
#ifexpr
[edit]To achieve this, we can performing a rounding operation used the #expr
function, and then use the result to determine the "if" operation.
For example:
{{#ifexpr: 11 > 10 | Greater than 10 | Not greater than 10 }}
→ Greater than 10
This first rounds 10.7 using its ones:
{{#expr: 10.7 round 0}}
→ 11
Then it uses the #ifexpr
to see if the result is greater than 10. If it is, the new result becomes "Greater than 10", else the result becomes "Not greater than 10".
Using a numf template
[edit]The numf template helps split numbers with a comma so it's more readable.
{{numf|2^52 + 1}}
→ 4,503,599,627,370,497{{numf|(2^52 + 1) round -1}}
→ 4,503,599,627,370,500{{numf|4503599627370495.5 round 0}}
→ 4,503,599,627,370,495.5
Rounding a decimal and displaying its resulting hex using a numfh template
[edit]To perform rounding on a decimal and display its resulting hex number, Template:Numfh is used.
For example:
{{numfh|123.7 round -2}}
→ 100 (ca. 1e2)1.9000000000000hex*2^6
The operation first determines the hex value for the decimal, 123.7, using the below:
{{hex|123.7}}
→1.eeccccccccccdhex*2^6
Then it rounds it to the hundreds, which results in 100.
Lastly, it converts the decimal, 100, to hex:
{{hex|100}}
→1.9000000000000hex*2^6
More examples
[edit]{{numfh|123.7 round -1}}
→ 120 (ca. 1.2e2)1.e000000000000hex*2^6
{{numfh|123.7 round 0}}
→ 124 (ca. 1.2e2)1.f000000000000hex*2^6
{{numfh|123.7 round 1}}
→ 123.7 (ca. 1.2e2)1.eeccccccccccdhex*2^6
{{numfh|123.7 round 300}}
→ 123.7 (ca. 1.2e2)1.eeccccccccccdhex*2^6