Display Number with SI prefixes

Perhaps you can use the following to produce a Quantity object:

val=0.000015783;
UnitConvert[val, "Micro"]

15.783


UnitConvert, Quantity, and SetPrecision can convert a numerical value of amperes to µA with 3 significant digits.

val = 0.000015783;
UnitConvert[Quantity[SetPrecision[val, 3],"Amperes"],"MicroAmperes"]
(* 15.8 µA *)

Change the amperes quantity to a string with StringReplace and TextString.

StringReplace["A"|" "->""]@TextString@
  UnitConvert[Quantity[SetPrecision[val,3],"Amperes"],"MicroAmperes"]
(* 15.8µ *)

We can use these methods for a function that converts a numerical ampere value to a quantity value with an SI prefix and designated number of significant digits. The function selects the SI prefix that corresponds to engineering notation. Values outside of the known prefixes are converted to amperes and adjusted for precision, but without a prefix.

sciPrefix[n_, sd_?IntegerQ] := Module[{
  prefix = Switch[Quotient[Log10[n], 3], 0,"",-1,"Milli",-2,"Micro",-3,"Nano"],
  v = SetPrecision[Quantity[n, "Amperes"], sd]},
  If[Head[prefix] === String,
    UnitConvert[v, prefix<>"Amperes"],
    v]]

Then:

sciPrefix[val, 3]
(* 15.8 µA *)

Table[sciPrefix[val*Power[10,e], 3], {e,-5,8}](* etc. *)

Add the string conversion steps to convert a numeric ampere value to a formatted string.

sciPrefixText[n_, sd_?IntegerQ] := Module[{
  prefix = Switch[Quotient[Log10[n], 3], 0,"",-1,"Milli",-2,"Micro",-3,"Nano"],
  v = SetPrecision[Quantity[n, "Amperes"], sd]},
  StringReplace["A"|" "->""]@TextString@If[Head[prefix]===String,
    UnitConvert[v, prefix<>"Amperes"],
    v]]

sciPrefixText[val, 3]
(* 15.8µ *)
sciPrefixText[val, 4]
(* 15.78µ *)

It’s easy to add SI prefixes by changing Switch. For example,

Switch[Quotient[Log10[n], 3], 1,”Kilo”,0,””,-1,”Milli”,-2,”Micro”,-3,”Nano”,-4,”Pico”]

Where the numbers are the integer powers of 1000 and the matching prefixes from mathworld.wolfram.com/SIPrefixes.html.


Something like:

si[val0_] := Module[{val = val0, count = 0},
  If[Abs@val > 1,
   While[Abs@val >= 10^3, count++; val /= 10^3];
   pre = Switch[count, 1, "k", 2, "mega", 3, "giga", 4, "tera", _, ""]
   ,
   While[Abs@val < 1, count++; val *= 10^3];
   pre = Switch[count, 1, "mili", 2, "\[Mu]", 3, "nano", 4, "pico", _,
      ""]
   ];
  StringForm["`` ``", NumberForm[val, 3], pre]
  ]

si[15.8 10^-6]
 15.8 μ

Note, the output is only for display, you can not use it for further calculations.

Tags:

Formatting