1
$\begingroup$

It's often useful for me to round numbers to some decimal place for printing on a graph or figure. I usually do this by:

RoundedNumber = Round[NumberToRound, 0.001]

But if the resultant rounding is say 1.2 from 1.19, I would like to keep the trailing zero; so 1.20. The reason being is that I represent by errors in bracketed notation -- where the number in brackets represents the error in the last digit. E.g. 1.20(2) -- so as you can see it is important to keep the trailing zero as 1.2(2) has a different meaning to 1.20(0)

Does anyone a way I can do this?

$\endgroup$
  • 4
    $\begingroup$ 1.99 cannot round to 1.2. Did you mean 1.19? Take a look at NumberForm. NumberForm[1.19, {2, 2}] = 1.20. $\endgroup$ – Rohit Namjoshi Dec 27 '18 at 22:54
  • $\begingroup$ @RohitNamjoshi Eugh, yes! Sorry that is a typo! And brilliant thanks for that, I've never had much success with NumberForm[...] until now! PS corrected in the original question... $\endgroup$ – Q.P. Dec 27 '18 at 23:07
  • $\begingroup$ Notice that NumberForm[1.186, {2, 2}] is also 1.20 while the correct answer seems to be 1.19 - is this true? Sure that NumberForm[1.186, {3, 2}] gives 1.19, but you must find some way of calculating the number of digits as input to NumberForm. $\endgroup$ – Vito Vanin Dec 28 '18 at 0:45
  • 2
    $\begingroup$ Also try NumberForm[1.186, {\[Infinity], 2}] for precisely two digits to the right of the decimal dot. $\endgroup$ – Henrik Schumacher Dec 28 '18 at 8:34
  • $\begingroup$ @Schumacher Congratulations. Full solution, simple, practical and works also with numbers whose absolute values are smaller than 1. Should post, for future reference, since the accepted solution does not correspond to the convention on rounding numbers. I did not find this use of infinity in the argument list in the documentation for NumberForm[ ]. $\endgroup$ – Vito Vanin Dec 30 '18 at 1:34
5
$\begingroup$

This may mostly do what you want. With num specifying the number you are rounding and prec specifying the number of digits past the decimal:

rounded[num_, prec_] := 
 PaddedForm[num, {IntegerPart[Log[10, Abs[num]]] + prec, prec}]

rounded[1.19, 2]
(*1.20*)

rounded[1.19, 3]
 (*1.190*)

rounded[500.5556877, 3]
(*500.560*)

rounded[500.5556877, 5]
(*500.55570*)

If you do not require a trailing zero and want regular rounding you can add 1 to first element of the PaddedForm list:

rounded1[num_, prec_] := 
 PaddedForm[num, {IntegerPart[Log[10, Abs[num]]] + prec + 1, prec}]
$\endgroup$
  • $\begingroup$ Nice answer and a useful function! Thanks. $\endgroup$ – Q.P. Dec 28 '18 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.