Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

autonumeric

Package Overview
Dependencies
Maintainers
2
Versions
145
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

autonumeric

autoNumeric is a library that provides live *as-you-type* formatting for international numbers and currencies. It supports most International numeric formats and currencies including those used in Europe, Asia, and North and South America.

  • 2.0.7
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
35K
decreased by-40.27%
Maintainers
2
Weekly downloads
 
Created
Source

What is autoNumeric?

autoNumeric is a library that provides live as-you-type formatting for international numbers and currencies.

NPM
NPM version Downloads Build Status Known Vulnerabilities Coverage Status
Gitter chat

The latest stable branch is 2.*.
For older stable versions, please take a look here, while for the latest development version, check the next branch.

Moreover, you can take a look at what could be the next features coming to autoNumeric on our project page (feel free to participate!).

Highlights

autoNumeric main features are :

  • Easy to use and configure
// Initialization
$('.myInput').autoNumeric('init', { currencySymbol : '$' });
  • Very high configurability (more than 30 options available)
// The options are...optional :)
const autoNumericOptionsEuro = {
    digitGroupSeparator        : '.',
    decimalCharacter           : ',',
    decimalCharacterAlternative: '.',
    currencySymbol             : '\u202f€',
    currencySymbolPlacement    : 's',
    roundingMethod             : 'U',
};

// Initialization
$('.myInput').autoNumeric('init', autoNumericOptionsEuro);
  • User experience oriented ; using autoNumeric just feels right and natural
  • Supports most international numeric formats and currencies
    (If the one you use is not supported yet, open an issue and we'll add it as soon as possible!)

And also:

  • Any number of different formats can be used at the same time on the same page.
    Each input can be configured by either setting the options as HTML5 data attributes, or directly passed as an argument in the Javascript code
  • The settings can easily be changed at any time using the update method or via a callback
  • autoNumeric supports most text elements, allowing you to place formatted numbers and currency on just about any part of the page
  • Pre-defined currency options allows you to directly use autoNumeric by skipping the option configuration step
  • 18 built-in methods gives you the flexibility needed to use autoNumeric to its maximum potential
  • More than 30 options allows you to customize the output format

With that said, autoNumeric supports most International numeric formats and currencies including those used in Europe, Asia, and North and South America.


Getting started

Installation

You can install autoNumeric with your preferred dependency manager:

# with `yarn` :
yarn add autonumeric
# or with `npm` :
npm install autonumeric

How to use?

Simply include jQuery and autoNumeric (in that order) in your html <header> tag.
No other file or library are required.

<script src="jquery.min.js" type="text/javascript"></script>
<script src="autoNumeric.min.js" type="text/javascript"></script>
<!-- You may also directly use a CDN :-->
<script src="https://cdn.jsdelivr.net/autonumeric/2.0.0/autoNumeric.min.js"></script>

Initialize autoNumeric with or without options :

// autoNumeric with the defaults options
$(selector).autoNumeric('init');

// autoNumeric with specific options being passed
$(selector).autoNumeric('init', { options }); 

// autoNumeric with pre-defined language options being passed
$(selector).autoNumeric('init', $.fn.autoNumeric.lang.French);

(See the available language list here)

You're done!

On which elements can it be used?

Here are the following supported input types:

  • text,
  • tel,
  • hidden, or
  • no type specified at all
<input type='text' value="1234.56">
<input type='tel' value="1234.56">
<input type='hidden' value="1234.56">
<input value="1234.56">

Note : the number type is not supported simply because autoNumeric formats numbers as strings (ie. '123.456.789,00 &#8364;') that this input type does not allow.

Options

Multiple options allow you to customize precisely how a form input will format your inputs as you type :

OptionDescriptionDefault Value
allowDecimalPaddingAllow padding the decimal places with zerostrue
currencySymbolCurrency symbol''
currencySymbolPlacementPlacement of the currency sign, relative to the number (as a prefix or a suffix)'p'
decimalCharacterDecimal separator character'.'
decimalCharacterAlternativeAllow to declare alternative decimal separator which is automatically replaced by the real decimal character (useful in countries where the keyboard numeric pad have a period as the decimal character)null
decimalPlacesOverrideMaximum number of decimal places (used to override decimal places set by the minimumValue & maximumValue values)null
decimalPlacesShownOnFocusExpanded decimal places visible when input has focusnull
defaultValueOverrideHelper option for the ASP.NET-specific postback issuenull
digitalGroupSpacingDigital grouping for the thousand separator'3'
digitGroupSeparatorThousand separator character','
emptyInputBehaviorDefine what to display when the input value is empty (possible options are focus, press, always and zero)'focus'
failOnUnknownOption This option is the 'strict mode' (aka 'debug' mode), which allows autoNumeric to strictly analyse the options passed, and fails if an unknown options is used in the settings object.false
formatOnPageLoadDetermine if the default value will be formatted on initializationtrue
leadingZeroControls the leading zero behavior (possible options are allow, deny and keep)'deny'
maximumValueMaximum possible value'9999999999999.99'
minimumValueMinimum possible value'-9999999999999.99'
negativeBracketsTypeOnBlurAdds brackets [], parenthesis (), curly braces {} or <> on negative values when unfocusednull
negativePositiveSignPlacementPlacement of negative/positive sign relative to the currency symbol (possible options are l (left), r (right), p (prefix) and s (suffix))null
noSeparatorOnFocusRemove the thousand separator, currency symbol and suffix on focusfalse
onInvalidPasteManage how autoNumeric react when the user tries to paste an invalid number (possible options are error, ignore, clamp, truncate or replace)'error'
outputFormatDefines the localized output format of the get, getString & getArray methodsnull
overrideMinMaxLimitsOverride minimum and maximum limits (possible options are ceiling, floor and ignore)null
roundingMethodMethod used for rounding (possible options are S, A, s, a, B, U, D, C, F, N05, U05 or D05)'S'
saveValueToSessionStorageAllow the decimalPlacesShownOnFocus value to be saved into session storagefalse
scaleDecimalPlacesThe number of decimal places when unfocusednull
scaleDivisorThis option decides the onfocus value and places the result in the input on focusoutnull
scaleSymbolSymbol placed as a suffix when unfocusednull
selectNumberOnlyDetermine if the select all keyboard command will select the complete input text, or only the input numeric valuefalse
showPositiveSignAllow the positive sign symbol + to be displayed for positive numbersfalse
showWarningsDefines if warnings should be showntrue
suffixTextAdditional text suffix that is added after the number''
unformatOnSubmitRemoves formatting on submit eventfalse

For more detail on how to use each options, please take a look at the detailed comments in the source code for the defaultSettings object.

Predefined language options

Sometime you do not want to have to configure every single aspect of your format, specially if it's a common one.
Hence, we provide multiple default options for the most common currencies.

You can use those pre-defined language option like so :

// ES6 way
$(selector).autoNumeric('init', an.getLanguages().French);

// jQuery way
$(selector).autoNumeric('init', $.fn.autoNumeric.lang.French);

Currently, the predefined options are :

Option name
:fr:French
:es:Spanish
:us:NorthAmerican
:uk:British
🇨🇭Swiss
:jp:Japanese
:cn:Chinese

If you feel a common currency option is missing, please create a pull request and we'll add it!

Methods

autoNumeric provides numerous methods to access and modify the input value, formatted or unformatted, at any point in time.
It does so by either providing access to those methods via the jQuery wrapper, or directly via the autoNumeric ES6 module.

jQuery plugin calls
MethodDescriptionCall example
initInitialize autoNumeric and attach the settings (options can be passed as a parameter). This must be run before other methods can be called.$(someSelector).autoNumeric('init', {options});
autoFormatcf. ES6 Module calls$(someSelector).autoFormat('1234.56', {options});
autoUnFormatcf. ES6 Module calls$(someSelector).autoUnFormat('1.234,56 €', {options});
autoValidatecf. ES6 Module calls$(someSelector).autoValidate({options});
defaultsReturn the default autoNumeric settings$.fn.autoNumeric.defaults
destroyStop and remove autoNumeric for the current element$(someSelector).autoNumeric("destroy");
getReturn the unformatted value as a string$(someSelector).autoNumeric('get');
getArraySerialize the whole form input array into an Array$(someSelector).autoNumeric('getArray');
getFormattedReturn the current formatted value$(someSelector).autoNumeric('getFormatted');
getLocalizedReturns the unformatted value, but following the outputFormat setting$(someSelector).autoNumeric('getLocalized');
getNumberReturn the input unformatted value as a real Javascript number$(someSelector).autoNumeric('getNumber');
getStringSerialize the whole form input array into a String$(someSelector).autoNumeric('getString');
langReturn all the predefined language options in one object$.fn.autoNumeric.lang
reSetRe-format inputs (handy right after form submission)$(someSelector).autoNumeric('reSet');
setSet the value given as a parameter, and formats it$(someSelector).autoNumeric('set', '12345.67');
unSetUnformat inputs (handy right before form submission)$(someSelector).autoNumeric('unSet');
updateUpdates the autoNumeric settings, which reformat the input on-the-fly$(someSelector).autoNumeric("update", {options});
wipeClear the value from sessionStorage (or cookie, depending on browser supports)$(someSelector).autoNumeric("wipe");
ES6 Module calls

First you need to get a reference to the autoNumeric object that you need to import:

import an from 'lib/autoNumeric.js';

Then you'll be able to use that object static methods:

MethodDescriptionCall example
areSettingsValidReturn true in the settings are validan.areSettingsValid({options})
formatFormat the given value without needing to initialize an autoNumeric input firstan.format('1234.56', {options})
getDefaultConfigReturn the default autoNumeric settingsan.getDefaultConfig()
getLanguagesReturn all the predefined language options in one objectan.getLanguages()
unFormatUnformat the given value without needing to initialize an autoNumeric input firstan.unFormat('1.234,56 €', {options})
validateCheck if the given option object is valid, and that each option is valid as well. This throws an error if it's not.an.validate({options})

Work is ongoing to export all the current jQuery-only methods into the ES6 module.

Questions

For questions and support please use the Gitter chat room or IRC on Freenode #autoNumeric.
The issue list of this repository is exclusively for bug reports and feature requests.


How to contribute?

Contributors and pull requests are welcome.
Feel free to contact us for any questions.

Get the latest source

git clone -b next https://github.com/BobKnothe/autoNumeric.git
# or the following if you are authentified on github :
# `git clone -b next git@github.com:BobKnothe/autoNumeric.git`

Make your changes

cd autoNumeric

First things first, in order to be able to compile the ES6 source to something that can be interpreted by the browsers, and get the tools (linter, test runners, etc.) used by the developers, you need to install them by doing :

yarn install

Note: you need to have yarn installed before executing this command.
You can install yarn globally by doing npm install -g yarn as root.

Once you made your changes, you can build the library with :

yarn build

This will generate the autoNumeric.js and autoNumeric.min.js files in the dist folder, that you'll then be able to use in the browsers.

If you want to clean the generated .js and .min.js files as well as development specific ones like coverage and log files, use :

yarn run clean

Note: do not use yarn clean as it's a different command entirely.

Run the mandatory tools for linting and testing

We strive to keep the tests green at all times. Hence whenever you change the source, be sure to :

  1. Write at least 2 tests for each change :
  • One that validate your changes
  • One that invalidate your changes
  1. Make sure all tests passes on all supported browsers (PhantomJS, Firefox, and Chrome)
  • Write unit tests and end-to-end tests
  1. Make sure eslint does not return any errors regarding the coding style.
How to test?

Tests must always be green :white_check_mark: before pushing. Any commit that make the tests fails will be ignored.
To run the tests, you have multiple options :

# Run unit testing as well as end-to-end testing
yarn test

# Run unit testing only
yarn test:unit

# Run end-to-end testing only
yarn test:e2e

# Run unit testing only...
yarn test:unitp   # ...with PhantomJS only
yarn test:unitf   # ...with Firefox only
yarn test:unitc   # ...with Chrome only

Behind the scene, all unit and end-to-end tests are written with Jasmine.
Karma is used to run the unit tests, while Webdriver.io is used to run end-to-end tests.

How to lint?

Linting allow us to keep a coherent code style in all the source files.
In order to check that everything is well formatted, run eslint with :

yarn lint

If any errors are shown, you can try to automatically correct them by running :

# Use the path of the faulty file there :
./node_modules/eslint/bin/eslint.js --fix src/autoNumeric.js
How to push?

Every changes that you pushed in its own branch in your personal autoNumeric copy should be based on the latest version of the next branch.

When you create a pull request, make sure to push against the next branch.

Your commit must not contain any generated files (ie. files in the /dist/ directory or logs).
Note: Generated dist files (ie. autoNumeric.js and autoNumeric.min.js) are built and force-added to the git repository only once for each official release on master.

Dependencies

Currently, autoNumeric depends on jQuery (which is pretty logical since it's a jQuery plugin ;P).
Some work is in progress to provide a jQuery-free version of autoNumeric.

Older versions

The previous stable autoNumeric version v1.9.46 can be found here.

For integration into Rails projects, you can use the autonumeric-rails project.

Documentation

A more detailed documentation can be found in the Documentation file.
For more examples and an option code generator (that may be outdated), take a look here.

Licence

autoNumeric is an MIT-licensed open source project, and its authors are credited in AUTHORS.md.


Feel free to donate via Paypal Donate or Patreon to support autoNumeric development.

Keywords

FAQs

Package last updated on 31 Jan 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc