5
$\begingroup$

NumberForm can be used to print Quantities to a specified precision. For example,

x=Quantity[5.123456789,"Meters"];
5.12346 m
Print[NumberForm[x,{4,2}]]
5.12 m

This does exactly what I want, but it has an undesirable effect for units with exponents. For example,

y=Quantity[5.123456789,"Meters"/"Seconds"^2];
5.12346 m/s^2
Print[NumberForm[y,{4,2}]]
5.12 m/s^2.00

I'd like the precision specification to apply to the quantity, not to the units. Is there a way to do that?

$\endgroup$
1
  • $\begingroup$ The problem I described in the question appears to have been resolved in Mathematica 9.0.1 $\endgroup$
    – Cassini
    Commented Jan 31, 2013 at 21:32

1 Answer 1

3
$\begingroup$

Perhaps you'd like to add this definition?

Unprotect[NumberForm];
Format[HoldPattern@NumberForm[Quantity[n_, u_], r___]] := 
  Quantity[NumberForm[n, r], u];
Protect[NumberForm];
$\endgroup$
6
  • $\begingroup$ That worked for me. Thank you!!! $\endgroup$
    – Cassini
    Commented Jan 13, 2013 at 18:18
  • 1
    $\begingroup$ This is a more general problem. I face it very often when, for example, I make a fitting of some data, and then print it together with the data and the fitting function. Assume I fit a data with a function f=a*Exp[-2t^2]. What can be simpler? Assume the result of fitting is a=0.123456. Assume I want to print it with two figures after comma, i.e. like this: 0.12*Exp[-2t^2]. I do it as NumberForm[f,{3,2}] and get 0.12*Exp[-2.00*t^2], which is not what I need. However, the workaround offered by Rojo is not universal enough to be used in all such cases, say, for any fitting function possible. $\endgroup$ Commented Jan 14, 2013 at 11:28
  • $\begingroup$ @AlexeiBoulbitch, yes, it's not universal. However, it would b nice to have a clear description of the most general problem you face and how would the general solution behaviour be. Perhaps it can be done :) $\endgroup$
    – Rojo
    Commented Jan 14, 2013 at 14:40
  • $\begingroup$ @AlexeiBoulbitch $\endgroup$
    – Rojo
    Commented Jan 14, 2013 at 19:22
  • $\begingroup$ Dear Rojo, I do not really know, what should I add more. The example I had in mind here is the case when I fit a list with some model function (such as f=a*Exp[-2t^2], for example typically, however, more complex), or any other, but then I want to show the plot of the list+fitting function. In this case I also place the formula of the fitting function as the epilog. Like here:Epilog -> Inset[Row[{Style["f(t)="], Style[NumberForm[f, {3, 2}]]}], Scaled[{0.8, 0.9}]]. This is typically done when the whole thing is subjected to manipulation and when I change the manipulation parameter $\endgroup$ Commented Jan 16, 2013 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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