Unicode Numbers In Javascript
Instalation and use
To install:
npm install @ull-esit-pl/uninums
To use it:
> uninums = require("@ull-esit-pl/uninums")
{ normalSpaces: [Function: normalSpaces],
normalDigits: [Function: normalDigits],
parseUniInt: [Function: parseUniInt],
parseUniFloat: [Function: parseUniFloat],
sortNumeric: [Function: sortNumeric] }
> uninums.parseUniInt('६.६')
6
> uninums.parseUniFloat('६.६')
6.6
> uninums.parseUniFloat('६.६e६')
6600000
> uninums.sortNumeric(['٣ dogs','١٠ cats','٢ mice'])
[ '٢ mice', '٣ dogs', '١٠ cats' ]
> uninums.normalDigits('٢ mice')
'2 mice'
> uninums.normalDigits('٣ dog')
'3 dog'
> uninums.normalDigits('١٠ cats')
'10 cats'
> uninums.normalDigits('٠۴६')
'046'
Unicode Numbers In Javascript
Blog:See also the blog: Unicode Numbers In Javascript Posted on December 1, 2010 by Roy Sharon
Description
Javascript supports Unicode strings, but parsing such strings to numbers is unsupported (e.g., the user enters a phone number using Chinese numerals).
uninums.js is a small utility script that implements five methods for handling non-ASCII numerals in Javascript:
Function | Description |
---|---|
normalDigits(s) | Normalizes string s by replacing all non-ASCII digits with ASCII digits.
|
normalSpaces(s) | Normalizes string s by replacing all whitespace characters with either a space (‘\x20′) or a newline (‘\n’) as appropriate:
As a special case, normalSpaces() also replaces CRLF to a single newline character. So normalSpaces(‘\r\n’) == ‘\n’. |
parseUniInt(s,r) | Returns the integer value at the start of string s , ignoring leading spaces and using radix r . This is equivalent to the behavior of Javascript’s internal parseInt() function, but also handles non-ASCII digits:
|
parseUniFloat(s) | Returns the float value at the start of string s , ignoring leading spaces. This is equivalent to the behavior of Javascript’s internal parseFloat() function, but also handles non-ASCII digits:
|
sortNumeric(a) | Sorts array a in place according to the numeric float values of its items:
Note that using Javascript’s internal sort() function will order ’10 cats’ before ’2 mice’ because it is string based rather than numeric. |
For further information on how these functions are implemented see here.
Using or modifying this project is subject to the MIT License.