10.4: Add custom units to the Unit Converter widget

May 25, '05 09:07:00AM

Contributed by: enkidu

Tiger only hintHere's how to add a new unit to the Unit Conversion widget. In our example, we will add the unit "Cup (US)" to the "Volume" section of conversions. From the command line, do this:

cd /Library/Widgets/Unit Converter.wdgt
Next, make a backup copy of the Conversions.js file:
sudo cp Conversions.js Conversions_backup.js
Now edit the Conversions.js file with your favorite editor (I use vim launched via sudo).

Inside the file, search for the Volume array declaration. It looks like this:

var Volume = [
    {name:'Cubic Feet',         toBase:linearForm(28.316846592),        fromBase:invLinForm(28.316846592)},
    {name:'Gallon (Imperial)',  toBase:linearForm(4.54609),             fromBase:invLinForm(4.54609)},
    {name:'Gallon (US)',        toBase:linearForm(3.785411784),         fromBase:invLinForm(3.785411784)},
    {name:'Quart (US)',         toBase:linearForm(0.94635294600000),    fromBase:invLinForm(0.94635294600000)},
    {name:'Pint (US)',          toBase:invLinForm(2.11337641886519),    fromBase:linearForm(2.11337641886519)},
    {name:'Fluid Ounce (US)',   toBase:invLinForm(33.81402270184300),   fromBase:linearForm(33.81402270184300)},
    {name:'Dram (US)',          toBase:invLinForm(270.51218161474401),  fromBase:linearForm(270.51218161474401)},
    {name:'Cubic Meter',        toBase:linearForm(1000.0),              fromBase:invLinForm(1000.0)},
    {name:'Liter',              toBase:linearForm(1.0),                 fromBase:invLinForm(1.0)}
];

Add your own custom entry for the Cup unit. The format is simple. The first value is the name, the second value is the conversion from the new unit to the base unit (in the case of Volume, the base unit is Liter, the last entry in the list). Use the invLinForm option for conversion through multiplication. The last value is the reverse conversion. If you used invLinForm for the second, you would use linearForm for the third, and vice versa.

In our case, since the Cup is half the size of a Pint, we can double the conversion factor of Pint:

    {name:'Cup (US)',          toBase:invLinForm(4.22675283773038),    fromBase:linearForm(4.22675283773038)},

Save the file. Relaunch the unit converter widget and enjoy your custom unit!

Some things to note:

[robg adds: I haven't tested this one.]

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050514222026454