To always have the latest version use
// @require https://update.greasyfork.org/scripts/519002/Units%20Converter.js
Documentation for the library and its usage:
Unit Conversion Library Documentation
Overview
This library provides a simple framework to convert units of measurement. It supports various unit types (e.g., length, weight, volume, temperature) and handles conversions with single or compound values.
Features
- Unit Conversion: Converts a numeric value from one unit to another.
- Compound Conversions: Handles cases with two values (e.g., "10x20 inches").
- Exponential Operations: Supports calculations like powers (e.g., "5^3").
- Unit Recognition: Uses a regex pattern to identify units and values from text input.
Usage
Example Input
"150 pounds" → Outputs: "68.03 kg"
"10x20 inches" → Outputs: "25.40 x 50.80 cm"
"5^3" → Outputs: "125 power"
Main Functions
Regex Matching for Units
const UnitType = "150 pounds".match(Units)[3].toLowerCase(); //Change "150 pounds" to the element that contains the string
- Extracts the unit type from user input.
Value Extraction
const UnitValue = "150 pounds".match(Units)[1].replaceAll(',', '.'); //Change "150 pounds" to the element that contains the string
const SecondUnitValue = "150 pounds".match(Units)[2]?.replaceAll(',', '.') || 0; //Change "150 pounds" to the element that contains the string
- Extracts numeric values (first and second, if available).
Value Conversion
const convertValue = (value, unitType) => {
const { factor, convert } = window.UConv[unitType] || {};
return convert ? convert(value) : value * factor;
};
- Converts a value from one unit to another using a predefined conversion map.
New Unit Detection
var NewUnit = window.UConv[UnitType]?.unit || UnitType;
- Determines the target unit for conversion.
Final Conversion Output
var ConvertedUnit = `${convertValue(parseFloat(UnitValue), UnitType).toFixed(2)}${SecondUnitValue != 0 ? ` x ${convertValue(parseFloat(SecondUnitValue), UnitType).toFixed(2)}` : ''}`;
- Produces the final converted value(s).
Special Cases
ConvertedUnit = "5^3".match(/\^(\d+\.?\d*)/)
? (NewUnit = 'power', Math.pow(parseFloat(UnitValue), parseFloat(Text.match(/\^(\d+\.?\d*)/)[1])))
: ConvertedUnit;
- Handles exponential calculations like
5^3
.
Display Conversion
ShowConvertion('Units', NewUnit, ConvertedUnit);
- Outputs the conversion result.
Adding New Units
To add new units, modify the addConversion
function in the UConv
library:
addConversion(['unit1', 'unit2'], 'targetUnit', conversionFactor, optionalConvertFunction);
Example:
addConversion(['pound', 'lb'], 'kg', 0.453592);
How It Works
- Input Parsing: The script uses regex to extract the unit type and numeric values from text input.
- Conversion: It looks up the appropriate conversion factor or custom conversion function from
UConv
.
- Output: Converts the values and returns the result in the desired format, supporting compound and exponential calculations.