Convert Western Numbers to Arabic Numerals Online with JavaScript and PHP
Create a seamless experience with our online tool for converting numbers into Arabic numerals (e.g., 123 → ١٢٣). Our platform not only offers instant conversion but also provides JavaScript and PHP code snippets, enabling developers to integrate numeral conversion functionality directly into their projects.
Contents
Demo: Convert Numbers to Arabic Numerals Online
Enter a number in the text box below, click the "Convert" button, and view the result displayed as an Arabic numeral.
PHP Function for Arabic Numeral Conversion
The following PHP code demonstrates how to convert Western numbers into Arabic numerals. This snippet handles input validation, supports decimals and negative signs, and ensures unsupported characters are flagged with meaningful error messages. Ideal for server-side number localization.
<?php
/**
* Convert a number to its Arabic numeral representation.
*
* @param mixed $number The input number, can be a string or numeric value.
* @return string The Arabic numeral representation.
* @throws InvalidArgumentException If the input is invalid or contains unsupported characters.
*/
function convertToArabicNumber($number): string {
// Validate input
if ($number === null) {
throw new Exception('Input cannot be null');
}
if (!is_numeric($number) && !is_string($number)) {
throw new Exception('Input must be a number or a string representing a number.');
}
// Convert the input to a trimmed string and remove unwanted characters
$numStr = str_replace([',', '_'], '', trim((string)$number));
// Mapping of Western/Latin numerals to Arabic numerals
$arabicNumeralMap = [
'0' => '٠',
'1' => '١',
'2' => '٢',
'3' => '٣',
'4' => '٤',
'5' => '٥',
'6' => '٦',
'7' => '٧',
'8' => '٨',
'9' => '٩',
'.' => '٫',
'-' => '−'
];
// Convert each character to its Arabic numeral equivalent
$arabicNumber = '';
foreach (str_split($numStr) as $char) {
if (!array_key_exists($char, $arabicNumeralMap)) {
throw new InvalidArgumentException("Unsupported character found: '$char'.");
}
$arabicNumber .= $arabicNumeralMap[$char];
}
return $arabicNumber;
}
PHP Example Usage
// Example Usage
try {
echo convertToArabicNumber(123.45) . "\n"; // Outputs: ١٢٣٫٤٥
echo convertToArabicNumber('-78.90') . "\n"; // Outputs: −٧٨٫٩٠
echo convertToArabicNumber('007') . "\n"; // Outputs: ٠٠٧
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Using PHP NumberFormatter
In PHP, you can achieve similar number formatting using the code NumberFormatter class, which is part of the intl
extension. Here is an equivalent way to convert numbers with localization:
<?php
// Make sure the intl extension is enabled
$number = 123456789;
// Create a NumberFormatter for Arabic (Egypt)
$formatter = new NumberFormatter('ar-EG', NumberFormatter::DECIMAL);
// Format the number
$formattedNumber = $formatter->format($number);
echo $formattedNumber; // Outputs: "١٬٢٣٤٬٥٦٧٫٨٩"
JavaScript Function for Arabic Numeral Conversion
Use this JavaScript function to convert Western numbers into Arabic numerals on the client side. It validates inputs, maps numerals using an object, and throws errors for unsupported characters. This lightweight and efficient solution is perfect for real-time web applications.
function convertToArabicNumber(number) {
// Validate input
if (number === null || number === undefined) {
throw new Error('Input cannot be null or undefined');
}
if (typeof number !== 'number' && typeof number !== 'string') {
throw new TypeError('Input must be a number or a string representing a number.');
}
// Convert the input to a string and remove commas and trim
const numStr = String(number).replace(/[,_]/g, '').trim();
// Mapping of Western/Latin numerals to Arabic numerals
const arabicNumeralMap = {
'0': '٠',
'1': '١',
'2': '٢',
'3': '٣',
'4': '٤',
'5': '٥',
'6': '٦',
'7': '٧',
'8': '٨',
'9': '٩',
'.': '٫',
'-': '−'
};
// Convert each character to its Arabic numeral equivalent
return numStr.split('').map(char => {
const arabicChar = arabicNumeralMap[char];
if (arabicChar === undefined) {
throw new Error(`Unsupported character: ${char}`);
}
return arabicChar;
}).join('');
}
JavaScript Usage Example
// Example usage
try {
console.log(convertToArabicNumber('100,000')); // Outputs: "١٠٠٠٠٠"
console.log(convertToArabicNumber('100_000')); // Outputs: "١٠٠٠٠٠"
console.log(convertToArabicNumber(123456)); // Outputs: "١٢٣٤٥٦"
console.log(convertToArabicNumber(-9876.54)); // Outputs: "-٩٨٧٦٫٥٤"
console.log(convertToArabicNumber('100-000')); // Outputs: Throws error (invalid format after cleaning)
} catch (error) {
console.error("Error:", error.message);
}
Using JavaScript toLocaleString
Number Formatting
JavaScript toLocaleString
allows you to easily format numbers, dates, and currencies based on the users locale. This is essential for applications catering to a global audience.
Example: Number Formatting
const number = 123456789;
console.log(number.toLocaleString('ar-EG')); // Outputs: "١٬٢٣٤٬٥٦٧٫٨٩"
Function Features
Both the JavaScript and PHP implementations of the number-to-Arabic conversion functions include the following features:
- Input Validation: The functions ensure inputs are valid numbers or strings representing numbers.
- Western-to-Arabic Mapping: Each numeral is mapped to its Arabic equivalent, including handling special characters like decimal points and negative signs.
- Error Handling: Unsupported or invalid characters are flagged with descriptive error messages.
- Versatility: The functions handle integers, floating-point numbers, and negative numbers.