1

I want to get the abbreviation for a Unit from its full name eg. "Newtons" => "N".

Using TraditionalForm on Quantity will show the abbreviation and doing the following will show the code returned by TraditionalForm:

Quantity["Newtons"] // TraditionalForm // InputForm
(* =>
FormBox[TemplateBox[{1}, QuantityUnit, 
   DisplayFunction -> 
    (TooltipBox[StyleBox[RowBox[{#1,  ,  N}], 
        ShowStringCharacters -> False], Unit: newtons] & ), 
   InterpretationFunction -> 
    (RowBox[{Quantity, [, RowBox[{#1, ,, "Newtons"}], ]}] & ), 
   SyntaxForm -> Mod], TraditionalForm]
*)

How can I extract the N from the above without parsing the string generated by using ToString on it?

Tyilo
  • 1,545
  • 13
  • 25
  • The boxes didn't copy completely; this is not valid input. Since I don't have Quantity in version 7 I cannot build your output for myself. Could you try copying again with a different method? Try copying as Input Text if you didn't use that already. – Mr.Wizard Aug 16 '13 at 00:33
  • @Mr.Wizard That gives the same output. – Tyilo Aug 16 '13 at 00:37

1 Answers1

2

This answer was made possible by rm-rf's help.

This may do what you want. I shall use ToBoxes to get valid box data to work with:

boxes = ToBoxes[ Quantity["Newtons"] ];

Cases[
  boxes, 
  StyleBox[RowBox[{__, label_}], "QuantityUnitTraditionalLabel"] :> label,
  -1
] // First
"\"N\""

You can use ToExpression or (for simple abbreviations) StringTake["\"N\"", {2, -2}] to strip the embedded quotation marks yielding "N".


Using the answer of this question allows you to quickly create a browser for all possible units:

Quantity["Newtons"];
units = StringReplace[Names["CalculateUnits`UnitCommonSymbols`*"], 
   "CalculateUnits`UnitCommonSymbols`" ~~ r_ :> r];

Manipulate[
 ToExpression @@ 
  Cases[MakeBoxes[#, TraditionalForm] &@Quantity[u], 
   StyleBox[RowBox[{__, label_}], "QuantityUnitTraditionalLabel"] :> 
    label, -1], {{u, "Newtons"}, units}]

Mathematica graphics

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371