JavaScript 中的区域感知数字转换

Locale aware number conversion in JavaScript(JavaScript 中的区域感知数字转换)
本文介绍了JavaScript 中的区域感知数字转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 JQuery 插件 可用于促进 NUMBER 本地化?也就是说,插件应该将数字翻译成它们的本地字形.

<上一页>阿拉伯语 |٤٣٢١ |1234印度语(泰卢固语/印地语) |౧౨౩౪౫/१२३४५ |12345

PS:我的要求是数字转换,而不是格式化.

解决方案

您可以使用像这样的简单函数来翻译来自阿拉伯数字:

function translateNumerals(input, target) {变种系统 = {梵文:2406,泰米尔文:3046,卡纳达文:3302,泰卢固语:3174,马拉地语:2406,马拉雅拉姆语:3430,oriya: 2918, gurmukhi: 2662, nagari: 2534, 古吉拉特语: 2790},zero = 48,//阿拉伯零的字符代码九 = 57,//阿拉伯九的字符代码offset = (systems[target.toLowerCase()] || zero) - 零,输出 = input.toString().split(""),我, l = 输出.长度, cc;对于 (i = 0; i < l; i++) {cc = 输出[i].charCodeAt(0);如果 (cc >= 零 && cc <= 九) {输出[i] = String.fromCharCode(cc + offset);}}返回 output.join("");}

然后这样称呼它

translateNumerals(12345, "Telugu")//"౧౨౩౪౫"translateNumerals(12345, "梵文")//"१२३४५"translateNumerals("foo", "Devanagari")//"foo"

阿拉伯数字的翻译同样简单.它只需要多一点管道.

上述函数知道任何目标系统中零的 charCode,并进行一些简单的数学运算,将阿拉伯数字逐个字符转换为该系统.

反向函数需要检查输入的每个字符.如果它落在任何源系统的 charCode 范围(即相应的零 + 9 的 charCode),它就知道所需的偏移量.减去偏移量将使您进入阿拉伯语范围.这很简单,我会留给你.

<小时>

编辑#1:既然你提到了jQuery,上面可以做成这样的插件:

jQuery.fn.extend({textTranslateNumerals: (function () {var translateNumerals = 函数(输入,目标){//上面的函数};返回函数(目标){//对于每个选定的元素...返回 this.each(function () {//...查看每个子节点并$(this).contents().each(function () {//...翻译文本节点,递归成元素if (this.nodeType === this.TEXT_NODE) {$(this).text(translateNumerals($(this).text(), target));} else if (this.nodeType === this.ELEMENT_NODE) {$(this).textTranslateNumerals(target);}});});};})()});

<小时>

编辑#2: FWIW,这是一个可以从任何源系统转换为任何目标系统的函数:

function translateNumerals(input, source, target) {变种系统 = {阿拉伯语:48,梵文:2406,泰米尔语:3046,卡纳达语:3302,泰卢固语:3174,马拉地语:2406,马拉雅拉姆语:3430,奥里亚语:2918,古尔穆基语:2662,纳加里语:2534,古吉拉特语:2790,},输出 = [],偏移量 = 0,零 = 0,九 = 0,字符 = 0;源 = source.toLowerCase();目标 = target.toLowerCase();if ( !(系统中的源 && 系统中的目标)||输入 == 空||typeof 输入 == "未定义" ||typeof 输入 == "对象" ) {返回输入;}输入 = input.toString();偏移量 = 系统 [目标] - 系统 [源];零 = 系统 [来源];九 = 系统[来源] + 9;for (var i=0, l=input.length; i

示例输出

translateNumerals("0123456789", "arabic", "malayalam")//"൦൧൨൩൪൫൬൭൮൯"translateNumerals("൦൧൨൩൪൫൬൭൮൯", "马拉雅拉姆语", "阿拉伯语")//"0123456789"translateNumerals("൦൧൨൩൪൫൬൭൮൯", "malayalam", "kannada")//"೦೧೨೩೪೫೬೭೮೯"translateNumerals("೦೧೨೩೪೫೬೭೮೯", "kannada", "nagari")//"০১২৩৪৫৬৭৮৯"translateNumerals("೦೧೨೩೪೫೬೭೮೯", "kannada", "gujarati")//"૦૧૨૩૪૫૬૭૮૯"translateNumerals("USD 13.56", "arabic", "nagari")//"USD ১৩.৫৬"

Is there a JQuery Plugin available that facilitates NUMBER LOCALIZATION ? That is , the plugin should translate numerals into their local glyphs.

Arabic               |     ٤٣٢١      |   1234

Indic (Telugu/Hindi) |  ౧౨౩౪౫/१२३४५   |  12345

PS : My requirement is number CONVERSION , not formatting .

解决方案

You could use a simple function like this one for the translation from Arabic numerals:

function translateNumerals(input, target) {
    var systems = {
            devanagari: 2406, tamil: 3046, kannada:  3302, 
            telugu: 3174, marathi: 2406, malayalam: 3430, 
            oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790
        },
        zero = 48, // char code for Arabic zero
        nine = 57, // char code for Arabic nine
        offset = (systems[target.toLowerCase()] || zero) - zero,
        output = input.toString().split(""),
        i, l = output.length, cc;

    for (i = 0; i < l; i++) {
        cc = output[i].charCodeAt(0);
        if (cc >= zero && cc <= nine) {
            output[i] = String.fromCharCode(cc + offset);
        }
    }
    return output.join("");
}

And call it like this

translateNumerals(12345, "Telugu")      // "౧౨౩౪౫"
translateNumerals(12345, "Devanagari")  // "१२३४५"
translateNumerals("foo", "Devanagari")  // "foo"

The translation to Arabic numerals is equally simple. It requires just a little more plumbing.

The above function knows the charCode of the Zero in any target system and does some simple math to do a character-by-character conversion from Arabic numerals to that system.

A reverse function would need to check each character of the input. If it falls the charCode range of any source system (i.e. the charCode of the respective Zero + 9) it knows the required offset. Subtracting the offset will get you into the Arabic range. This is pretty trivial and I'll leave it to you.


EDIT #1: Since you mentioned jQuery, the above could be made into a plugin like this:

jQuery.fn.extend({
    textTranslateNumerals: (function () {
        var translateNumerals = function (input, target) {
            // the above function
        };
        return function (target) {
            // for each selected element...
            return this.each(function () {
                // ...look at each child node and
                $(this).contents().each(function () {
                    // ...translate text nodes, recurse into elements
                    if (this.nodeType === this.TEXT_NODE) {
                        $(this).text(translateNumerals($(this).text(), target));
                    } else if (this.nodeType === this.ELEMENT_NODE) {
                        $(this).textTranslateNumerals(target);
                    }
                });
            });
        };
    })()
});


EDIT #2: FWIW, here is a function that can convert from any source system into any target system:

function translateNumerals(input, source, target) {
  var systems = {
    arabic:       48,
    devanagari: 2406, tamil: 3046, kannada:  3302, telugu: 3174, marathi:  2406,
    malayalam:  3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
  },
  output = [], offset = 0, zero = 0, nine = 0, char = 0;

  source = source.toLowerCase();
  target = target.toLowerCase();

  if ( !(source in systems && target in systems) 
       || input == null 
       || typeof input == "undefined" || typeof input == "object" ) {
    return input;
  }

  input  = input.toString();
  offset = systems[target] - systems[source];
  zero   = systems[source];
  nine   = systems[source] + 9;

  for (var i=0, l=input.length; i<l; i++) {
    var char = input.charCodeAt(i);

    if (char >= zero && char <= nine) {
      output.push( String.fromCharCode(char + offset) );
    } else {
      output.push( input[i] );
    }
  }
  return output.join("");
}

Sample outputs

translateNumerals("0123456789", "arabic", "malayalam")  // "൦൧൨൩൪൫൬൭൮൯"
translateNumerals("൦൧൨൩൪൫൬൭൮൯", "malayalam", "arabic")  // "0123456789"
translateNumerals("൦൧൨൩൪൫൬൭൮൯", "malayalam", "kannada") // "೦೧೨೩೪೫೬೭೮೯"
translateNumerals("೦೧೨೩೪೫೬೭೮೯", "kannada", "nagari") // "০১২৩৪৫৬৭৮৯"
translateNumerals("೦೧೨೩೪೫೬೭೮೯", "kannada", "gujarati") // "૦૧૨૩૪૫૬૭૮૯"
translateNumerals("USD 13.56", "arabic", "nagari") // "USD ১৩.৫৬"

这篇关于JavaScript 中的区域感知数字转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)