4
$\begingroup$

How to get an output of number form of a given TOTAL digit?

For example, a total digit of 3, then one get

  • 1.00 for 1.

  • 10.0 for 10.

  • 100. for 100.

and so on.

I try NumberForm[1., 3] but only get 1.. Of course I can use NumberForm[1., {1, 2}] to get 1.00 but then for 10. I need to use NumberForm[10.,{2, 1}] and for 100 I need to use NumberForm[100., {3, 0}], which is not automatic and depends on the certain number i input. So is there any way to get an output of number format with a fixed TOTAL digits that does not depends on the specific input?

$\endgroup$
2
  • $\begingroup$ How many total digits do you need ? $\endgroup$
    – Lotus
    Commented Aug 23, 2018 at 10:49
  • $\begingroup$ 4 digits is enough for my current use. :) $\endgroup$
    – atoman
    Commented Aug 23, 2018 at 10:52

2 Answers 2

5
$\begingroup$

You can also use SetPrecision in between.

f[z_] := NumberForm[SetPrecision[z, 4], 4];
f /@ {1/10, 1, 10, 100}

{0.1000, 1.000, 10.00, 100.0}

It is one of the great miracles why this does not work for machine precision numbers.

$\endgroup$
2
  • $\begingroup$ SetPrecision is exactly what i want. Thanks. :) $\endgroup$
    – atoman
    Commented Aug 23, 2018 at 12:35
  • $\begingroup$ You're welcome. Be careful as SetPrecision returns the input rounded, hence a different number. That does not matter if you use that only for displaying purposes. Use the result of SetPrecision in further computation if you really know what you are doing. $\endgroup$ Commented Aug 23, 2018 at 12:39
5
$\begingroup$

How about this ? I think this is what you want. Feel free to let me know if otherwise:

fixform[n_, dig_] := Module[{},
  NumberForm[
   n, {Length[IntegerDigits[Rationalize[n]]], 
    dig - Length[IntegerDigits[Rationalize[n]]]}]
  ]

n is the number and dig is the Total number of digits you want.

For example:

fixform[10., 4]

(* 10.00 *)

fixform[100., 4]

(* 100.0 *)

fixform[1., 4]

(* 1.000 *)
$\endgroup$

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.