4

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?

atoman
  • 147
  • 7

2 Answers2

5

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 *)
Lotus
  • 2,671
  • 11
  • 10
5

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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
  • SetPrecision is exactly what i want. Thanks. :) – atoman Aug 23 '18 at 12:35
  • 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. – Henrik Schumacher Aug 23 '18 at 12:39