Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
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 0:33
    
@Mr.Wizard That gives the same output. –  Tyilo Aug 16 '13 at 0:37
add comment

1 Answer

up vote 2 down vote accepted

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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