Javascript input number format

Natively Format JavaScript Numbers

When I’ve needed to format numbers in JavaScript I usually used Number.prototype.toFixed() , found a 3rd party library, or manually manipulated the number to suite my needs. However, with modern browsers, there’s a lot of really interesting capabilities you could start using with Number.prototype.toLocaleString() or Intl.NumberFormat . The following is a screenshot of the cross browser support from caniuse.com.

NOTE: Although the support looks pretty good from the above image, some of the options ( compactDisplay , currencySign , notation , signDisplay , unit , and unitDisplay ) are not supported in Safari (see compat table from MDN). However, thankfully there’s a polyfill you can use from Format.JS.

Quick 6 minute Overview

Number.prototype.toLocaleString()

The Number.prototype.toLocaleString() method takes two optional parameters of locales and options . If you don’t pass either, you’ll get the browser’s default locale. We’ll focus on the options parameter in the following sections.

const number = 12345.6789; console.log(number.toLocaleString()); // 12,345.679 (defaults to the "en-US" locale in my case) console.log(number.toLocaleString('de-DE')); // 12.345,679 

Currency Format

Formatting numbers is great and all, but what about fancy stuff like money. Well, that’s were the 2nd optional options parameter comes into play. If you supply a property of < style: "currency" >and a valid currency (an ISO 4217 currency code) then you’ll get a nicely formatted currency with locale support!

NOTE: There is no default currency code, so you’ll get an error if you don’t provide one.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  style: 'currency', currency: 'USD', >), ); // $12,345.68 console.log( number.toLocaleString('de-DE',  style: 'currency', currency: 'EUR', >), ); // 12.345,68 € console.log( number.toLocaleString('ja-JP',  style: 'currency', currency: 'JPY', >), ); // ¥12,346 

Significant Digits

Sometimes you want to control how many digits are significant in a number. You might think of this as Frontend Estimation. You can provide a minimumSignificantDigits (defaults to 1 ) or a maximumSignificantDigits (defaults to 21 ).

const number = 12345.6789; console.log( number.toLocaleString('en-US',  maximumSignificantDigits: 1, >), ); // 10,000 console.log( number.toLocaleString('fr-FR',  maximumSignificantDigits: 3, >), ); // 12 300 

Unit Support

Unit support is one of those things that I wouldn’t have expected to be a feature, but is pretty cool to have. You can mix and match locales along with units of measurement. You can find a full list of possible units from the ECMAScript specification. You can also provide a unitDisplay of long , short (default), or narrow to control how verbose the unit is displayed.

NOTE: This is one of those features that is not supported by Safari. Also there is no default value for unit , so if style is set to unit then one must be provided.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  style: 'unit', unit: 'mile-per-hour', >), ); // 12,345.679 mph console.log( number.toLocaleString('fr-FR',  style: 'unit', unit: 'liter', unitDisplay: 'long', >), ); // 12 345,679 litres 

Compact Notation

I found this amusing when I realized this feature existed. Not too long ago I needed something like this to abbreviate large numbers. I ended up finding a snippet of code online to get the job done, but now I know I could have used < notation: "compact" >! It also takes an optional compactDisplay that can be set to short (default) or long .

NOTE: This is one of those features that is not supported in Safari.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  notation: 'compact', compactDisplay: 'short', >), ); // 12K console.log( number.toLocaleString('en-US',  notation: 'compact', compactDisplay: 'long', >), ); // 12 thousand 

Percents

Having percent support is probably not a surprise to you, but it is handy to have especially since it is locale aware (as all the other options are). It gets a little bit nicer because you can also provide other options such as minimumFractionDigits (defaults to 0 or 2 for currency) or maximumFractionDigits to control how many fraction digits to use.

const number = 0.1234; console.log( number.toLocaleString('en-US',  style: 'percent', minimumFractionDigits: 2, >), ); // 12.34% 

Accounting

I don’t typically show negative currency with parenthesis, but apparently that is a common approach for those that do a lot of accounting. I probably won’t use this, but it’s good to know that it’s an option in case I ever do.

NOTE: This is one of those features that is not supported in Safari.

const number = -123.456; console.log( number.toLocaleString('en-US',  style: 'currency', currency: 'USD', currencySign: 'accounting', signDisplay: 'always', >), ); // ($123.46) 

Intl.NumberFormat

So, instead of using Number.prototype.toLocaleString() you could also use the Intl.NumberFormat constructor and then call the format method to format your numbers. However, that might confusing and may make you question which technique you should use. If you find yourself needing to format many numbers over and over again with the same locale and same options, then using Intl.NumberFormat is preferable for performance reasons.

«When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property.» —Number.prototype.toLocaleString()

const numberFormat = new Intl.NumberFormat('en-US',  style: 'unit', unit: 'mile-per-hour', >); console.log(numberFormat.format(12345.6789)); // 12,345.679 mph console.log(numberFormat.format(2345.67891)); // 2,345.679 mph 

Playground

For more information about all of these options and browser support, check out the Intl.NumberFormat() constructor page on MDN.

Источник

Javascript input number format

Fork me on GitHub

Credit card number formatting

var cleave = new Cleave('.input-element', < creditCard: true, onCreditCardTypeChanged: function (type) < // update UI . >>);

Phone number formatting

var cleave = new Cleave('.input-element', < phone: true, phoneRegionCode: '' >);

Date formatting

var cleave = new Cleave('.input-element', < date: true, delimiter: '-', datePattern: ['Y', 'm', 'd'] >);
var cleave = new Cleave('.input-element', < date: true, datePattern: ['m', 'y'] >);

Time formatting

var cleave = new Cleave('.input-element', < time: true, timePattern: ['h', 'm', 's'] >);
var cleave = new Cleave('.input-element', < time: true, timePattern: ['h', 'm'] >);

Numeral formatting

var cleave = new Cleave('.input-element', < numeral: true, numeralThousandsGroupStyle: 'thousand' >);

Custom options

var cleave = new Cleave('.input-element', < blocks: [4, 3, 3, 4], uppercase: true >);
var cleave = new Cleave('.input-element', < delimiter: '·', blocks: [3, 3, 3], uppercase: true >);
var cleave = new Cleave('.input-element', < delimiters: ['.', '.', '-'], blocks: [3, 3, 3, 2], uppercase: true >);
var cleave = new Cleave('.input-element', < prefix: 'PREFIX', delimiter: '-', blocks: [6, 4, 4, 4], uppercase: true >);

ReactJS component

import React from 'react'; import ReactDOM from 'react-dom'; import Cleave from 'cleave.js/react'; class MyComponent extends React.Component < onChange(event) < // formatted pretty value console.log(event.target.value); // raw value console.log(event.target.rawValue); >render() < return ( > onChange= /> ); > > 

Источник

JavaScript Number Format

In the article javascript number format, you will learn how to format numbers in JavaScript using some built-in and custom functions. We also work on precision and rounding of numbers.

1. Number Formatting Introduction

In JavaScript, we do not have integer , float , or double data types for numbers like in Java, C, or C++.

Instead, JavaScript uses a Number data type which is always double. The number data type is used to represent numeric values which represent both integer and floating-point numbers.

While programming we generally face situations like converting a long float value to a precision of 2 or 3. Like 3.141592 => 3.14 .

And sometimes you have to convert a general big number into a comma-separated number like 1000000000 => 1,000,000,000 or convert a number to some currency system, like 100 => $100 .

These problems are shown in the image below and can be solved by formatting numbers.

javascript number format

2. Number Format Javascript — Decimal Precision

While doing some complex calculations the numbers that we play with are generally in a long decimal format which is not readable. So we round these decimal points to a certain precision.

JavaScript provides a built-in method Number.toFixed() to format a number to a specified number of decimal places.

The toFixed() method takes 1 argument which is the number of decimal places to be precise.

let num = 12.345678; // default toFixed() method console.log(num.toFixed()); // 12 // 2 decimal places console.log(num.toFixed(2)); // 12.35 // 3 decimal places console.log(num.toFixed(3)); // 12.346 // 6 decimal places console.log(num.toFixed(4)); // 12.3457

You can also expand the number by giving a large number fixed place value.

let num = 34.567; console.log(num.toFixed(5)); // 34.56700 console.log(num.toFixed(10)); // 34.5670000000

3. JavaScript Number Format with Commas

To format a number with a comma means to separate the digits of a number by a comma at every 3rd digit like 123456789 => 1,234,567,890 .

This way it becomes quite easy to read the number in terms of thousands, millions, billions, etc.

Another style of separating number is by placing comma at like 123456789 => 1,23,45,67,890 . First comma at 3rd digit, then all at every 2nd digit.

3.1. Using toLocaleString() Method

These formats can be achieved by using the num.toLocaleString() method.

It accepts 2 optional arguments: locale and options .

The default value of locale is en-US .

The locale can be any of the following:

let num = 7323452568.283; // US system en-US var usFormat = num.toLocaleString('en-US'); console.log(usFormat); // 7,323,452,568.283 // India system hi-IN var inFormat = num.toLocaleString('hi-IN'); console.log(inFormat); // 7,32,34,52,568.283 // Egypt system ar-EG var egFormat = num.toLocaleString('ar-EG'); console.log(egFormat); // ٧٬٣٢٣٬٤٥٢٬٥٦٨٫٢٨٣

The position of the comma can be changed by different locales like the ‘en-US’ separates numbers with a comma at every 3 digits while ‘hi-IN’ uses a comma at every 2 digits (the last 3 digits are not separated).

3.2. Custom Function For Comma Separation

You can also create your own custom function that takes a number and returns a comma-separated number.

Our Javascript function will accept a number and return a comma-separated number at every 3 digits.

The steps to create the function are as follows:

  1. Check if the number is decimal. If it is decimal, then take digits before the decimal point because we only need to place a comma before the decimal point.
  2. Check if the number is negative. If it is negative, then remove the sign for now.
  3. Create a loop to iterate through the number and place a comma at every 3 digits.
  4. Add sign back if it was negative. Also, add a decimal point and decimal digits if it was decimal.
  5. Finally, return the number.
// Custom function to separate comma function separateComma(val) < // remove sign if negative var sign = 1; if (val < 0) < sign = -1; val = -val; >// trim the number decimal point if it exists let num = val.toString().includes('.') ? val.toString().split('.')[0] : val.toString(); let len = num.toString().length; let result = ''; let count = 1; for (let i = len - 1; i >= 0; i--) < result = num.toString()[i] + result; if (count % 3 === 0 && count !== 0 && i !== 0) < result = ',' + result; >count++; > // add number after decimal point if (val.toString().includes('.')) < result = result + '.' + val.toString().split('.')[1]; >// return result with - sign if negative return sign < 0 ? '-' + result : result; >let num1 = 12345678; console.log(separateComma(num1)); // decimal number let num2 = -723694769.2343; console.log(separateComma(num2));

The same function can be created using the regular expression and replace method.

function commaSeparateNumber(val) < // remove sign if negative var sign = 1; if (val < 0) < sign = -1; val = -val; >// trim the number decimal point if it exists let num = val.toString().includes('.') ? val.toString().split('.')[0] : val.toString(); while (/(\d+)(\d)/.test(num.toString())) < // insert comma to 4th last position to the match number num = num.toString().replace(/(\d+)(\d)/, '$1' + ',' + '$2'); > // add number after decimal point if (val.toString().includes('.')) < num = num + '.' + val.toString().split('.')[1]; >// return result with - sign if negative return sign < 0 ? '-' + num : num; >// decimal number let num1 = 77799; console.log(commaSeparateNumber(num1)); // decimal number let num2 = -72364769.1234; console.log(commaSeparateNumber(num2));

4. JavaScript Number Format Currency

JavaScript has a built-in method that can be used to format numbers for currency, it is Intl.NumberFormat() .

It is part of the Intl (international) object. The Intl.NumberFormat() method creates an object that is language sensitive and can be used to format numbers for currency.

It accepts 2 optional arguments: locale (en-US, hi-IN, etc) and options ().

const number = 76346.45; // United state $ let num = new Intl.NumberFormat('en-US', < style: 'currency', currency: 'USD' >).format(number); console.log(num); // Indian rupee ₹ num = new Intl.NumberFormat('hi-IN', < style: 'currency', currency: 'INR' >).format(number); console.log(num);

The same is also achievable using the toLocaleString() method.

var number = 76346.45; // request a currency format var num = number.toLocaleString('hi-IN', < style: 'currency', currency: 'INR' >) console.log(num); // United state $ num = number.toLocaleString('en-US', < style: 'currency', currency: 'USD' >) console.log(num);

5. Conclusion

In this article, we learned number format javascript methods. JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl.NumberFormat() method to format the number with currency.

You can also create your own custom function to format the number. This article covers all types of number conversion.

Источник

Читайте также:  Define in php example
Оцените статью