@verzonix/conversion v0.0.13
Verzonix Conversion
Verzonix Conversion is a TypeScript-based React library that provides localized conversion and formatting utilities for currency, dates, numbers, percentages, phone numbers, and geographical data (countries, states, and cities).
Note:
The library supports the following locales:en-US
,en-GB
, anden-IN
.
The locale is determined by: 1.navigator.language
2. A local storage key:LOCALIZATION_STORAGE_KEY
3. Alanguage
prop passed to theConversionProvider
Important: Ensure that the options used for formatting match those used for parsing.
Table of Contents
Installation
To install Verzonix Conversion in your project, run:
# Using npm
npm install verzonix-conversion
# Or using Yarn
yarn add verzonix-conversion
Usage
After installation, import and use the conversion functions in your React components. Both formatters and parsers are provided.
The locale is determined from:
1. navigator.language
2. Local storage key: LOCALIZATION_STORAGE_KEY
3. The language
prop passed to the ConversionProvider
1. Number Formatting
Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getFormattedNumber | Formats a number as a string | (value: number, options?: FormatNumberExtraParams) | string |
getParsedFormattedNumber | Parses a formatted number string back to a number | (value: string, options?: FormatNumberExtraParams) | number |
FormatNumberExtraParams
Option | Type | Default | Description |
---|---|---|---|
decimalPlaces | number | 2 | Number of decimal places to show |
useGrouping | boolean | true | Whether to use grouping separators (e.g., thousands separators) |
language | LOCALIZED_CONVERSION_LANGUAGES | - | Determines formatting based on locale (e.g., en-IN formats 100000 as 1,00,000 ) |
Usage Example
import { getFormattedNumber, getParsedFormattedNumber } from '@verzonix/conversion';
const value = 1234567.89;
const options = { decimalPlaces: 2, useGrouping: true };
const formattedNumber = getFormattedNumber(value, options);
console.log(formattedNumber); // e.g., "1,234,567.89"
const parsedNumber = getParsedFormattedNumber(formattedNumber, options);
console.log(parsedNumber); // 1234567.89
2. Percentage Formatting
Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getFormattedPercentage | Formats a number as a percentage string | (value: number, options?: FormatPercentageOptions) | string |
getParsedPercentage | Parses a formatted percentage string back to a number | (value: string, options?: FormatPercentageOptions) | number |
FormatPercentageOptions
Option | Type | Default | Description |
---|---|---|---|
decimalPlaces | number | 2 | Number of decimal places to show |
useGrouping | boolean | true | Whether to use grouping separators |
language | LOCALIZED_CONVERSION_LANGUAGES | - | Determines formatting based on locale |
Usage Example
import { getFormattedPercentage, getParsedPercentage } from '@verzonix/conversion';
const value = 0.1234;
const options = { decimalPlaces: 2, useGrouping: true };
const formattedPercentage = getFormattedPercentage(value, options);
console.log(formattedPercentage); // "12.34%"
const parsedPercentage = getParsedPercentage(formattedPercentage, options);
console.log(parsedPercentage); // 0.1234
3. Currency Formatting
Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getFormattedCurrency | Formats a number as a currency string | (value: number, options?: FormatCurrencyExtraParams) | string |
getParsedFormattedCurrency | Parses a formatted currency string back to a number | (value: string, options?: FormatCurrencyExtraParams) | number |
getCurrencySymbol | Gets the currency symbol for the current locale | None | string |
FormatCurrencyExtraParams
Option | Type | Default | Description |
---|---|---|---|
decimalPlaces | number | 2 | Number of decimal places to show |
useGrouping | boolean | true | Whether to use grouping separators |
language | LOCALIZED_CONVERSION_LANGUAGES | - | Determines formatting based on locale (e.g., en-US outputs "$1,234.56") |
Usage Example
import { getFormattedCurrency, getParsedFormattedCurrency, getCurrencySymbol } from '@verzonix/conversion';
const value = 1234.56;
const options = { decimalPlaces: 2, useGrouping: true };
const formattedCurrency = getFormattedCurrency(value, options);
console.log(formattedCurrency); // e.g., "$1,234.56"
const parsedCurrency = getParsedFormattedCurrency(formattedCurrency, options);
console.log(parsedCurrency); // 1234.56
const currencySymbol = getCurrencySymbol();
console.log(currencySymbol); // e.g., "$"
4. Date and Time Formatting
Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getFormattedDateAndTime | Formats a date and time | (date: Date, options?: FormatDateAndTimeExtraParams) | string |
getInputFormattedDateAndTime | Formats a date string based on locale | (dateString: string, options?: Omit<FormatDateAndTimeExtraParams, 'language'>) | number |
getTimeStampFromDateString | Gets a timestamp from a date string | (dateString: string) | number |
getStartofCurrentDay | Gets the timestamp for the start of the current day | None | Timestamp |
getEndofCurrentDay | Gets the timestamp for the end of the current day | None | Timestamp |
getStartofCurrentWeek | Gets the timestamp for the start of the current week | None | Timestamp |
getEndofCurrentWeek | Gets the timestamp for the end of the current week | None | Timestamp |
getStartofCurrentMonth | Gets the timestamp for the start of the current month | None | Timestamp |
getEndofCurrentMonth | Gets the timestamp for the end of the current month | None | Timestamp |
getStartofCurrentQuarter | Gets the timestamp for the start of the current quarter | None | Timestamp |
getEndofCurrentQuarter | Gets the timestamp for the end of the current quarter | None | Timestamp |
getStartofCurrentYear | Gets the timestamp for the start of the current year | None | Timestamp |
getEndofCurrentYear | Gets the timestamp for the end of the current year | None | Timestamp |
getStartofLastNDaysFromToday | Gets the timestamp for the start of the last N days from today | (days: number) | Timestamp |
getEndofLastNDaysFromToday | Gets the timestamp for the end of the last N days from today | (days: number) | Timestamp |
FormatDateAndTimeExtraParams
Option | Type | Default | Description |
---|---|---|---|
showDate | boolean | true | Whether to display the date |
showTime | boolean | - | Whether to display the time |
is12Hour | boolean | - | Use 12-hour time format |
showMonth | boolean | - | Whether to display the month |
showYear | boolean | - | Whether to display the year |
showSeconds | boolean | - | Whether to display seconds |
dayFormat | DAY_FORMAT (enum) | - | Format for the day (e.g., numeric, long) |
monthFormat | MONTH_FORMAT (enum) | - | Format for the month (e.g., numeric, long) |
yearFormat | YEAR_FORMAT (enum) | - | Format for the year |
hourFormat | HOUR_FORMAT (enum) | - | Format for the hour |
minuteFormat | MINUTE_FORMAT (enum) | - | Format for minutes |
secondFormat | SECOND_FORMAT (enum) | - | Format for seconds |
representationFormat | REPRESENTATION_FORMAT (enum) | - | Overall representation format |
timeZone | string | - | Time zone to use for formatting |
language | LOCALIZED_CONVERSION_LANGUAGES | - | Determines formatting based on locale |
Usage Example
import { getFormattedDateAndTime, getTimeStampFromDateString } from '@verzonix/conversion';
const date = new Date('2023-05-15T14:30:00');
const options = { showDate: true, showTime: true, is12Hour: true, showSeconds: true };
const formattedDate = getFormattedDateAndTime(date, options);
console.log(formattedDate); // e.g., "Monday, May 15, 2023, 2:30:00 PM"
const timestamp = getTimeStampFromDateString('2023-05-15T14:30:00');
console.log(timestamp); // e.g., 1684159800000
5. Phone Number Formatting
Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getFormattedPhoneNumber | Formats a phone number | (phoneNumber: string, options?: FormatPhoneNumberOptions) | { countryCode: string; phoneNumber: string } |
isValidPhoneNumber | Checks if the phone number is valid | (phoneNumber: string, options?: FormatPhoneNumberOptions) | boolean |
getFormattedInputPhoneNumber | Formats a phone number for input fields | (phoneNumber: string, options?: FormatPhoneNumberOptions) | string |
getParsedPhoneNumber | Parses a formatted phone number | (phoneNumber: string, options?: FormatPhoneNumberOptions) | { countryCode: string; phoneNumber: string } |
getDefaultCountryCode | Returns the default country code | None | string |
FormatPhoneNumberOptions
Option | Type | Default | Description |
---|---|---|---|
formatType | PHONE_NUMBER_FORMAT_TYPE | PHONE_NUMBER_FORMAT_TYPE.INTERNATIONAL | Format type for the phone number |
language | LOCALIZED_CONVERSION_LANGUAGES | - | Language used for formatting |
type | FORMAT_PHONE_NUMBER_TYPE | - | Specific phone number format type |
region | string | - | Region information for formatting |
countryCode | string | number | - | Country code to use for the phone number |
ParsedPhoneNumber Structure
Property | Type | Description |
---|---|---|
countryCode | string | The country code of the phone number |
nationalNumber | string | The national number part of the phone number |
extension | string | undefined | The extension of the phone number (if any) |
regionCode | string | The region code of the phone number |
Usage Example
import { getFormattedPhoneNumber, getParsedPhoneNumber, getDefaultCountryCode, PHONE_NUMBER_FORMAT_TYPE } from '@verzonix/conversion';
const phoneNumber = '1234567890';
const options = { formatType: PHONE_NUMBER_FORMAT_TYPE.NATIONAL };
const formattedPhoneNumber = getFormattedPhoneNumber(phoneNumber, options);
console.log(formattedPhoneNumber); // e.g., { countryCode: '1', phoneNumber: '2345678901' }
const parsedPhoneNumber = getParsedPhoneNumber(formattedPhoneNumber, options);
console.log(parsedPhoneNumber);
// e.g., { countryCode: '1', nationalNumber: '2345678901', extension: undefined, regionCode: 'US' }
const defaultCountryCode = getDefaultCountryCode();
console.log(defaultCountryCode); // e.g., "US"
6. Geographical Data
These functions leverage the country-state-city npm package to provide country, state, and city data.
Country Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getAllCountries | Returns all countries | None | Country[] |
getCountryByCode | Returns a country by ISO code | (isoCode: string) | Country |
Usage Example:
import { Country } from "country-state-city";
const countries = Country.getAllCountries();
console.log("Countries:", countries);
// Sample Output:
// [
// {
// name: "United States",
// isoCode: "US",
// phonecode: "1",
// flag: "🇺🇸",
// currency: "USD",
// latitude: "38.0000",
// longitude: "-97.0000"
// },
// ...more countries
// ]
const country = Country.getCountryByCode("US");
console.log("Country (US):", country);
// Sample Output:
// {
// name: "United States",
// isoCode: "US",
// phonecode: "1",
// flag: "🇺🇸",
// currency: "USD",
// latitude: "38.0000",
// longitude: "-97.0000"
// }
State Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getStatesOfCountry | Returns all states of a given country | (countryIsoCode: string) | State[] |
getStateByCodeAndCountry | Returns a state by code for a given country | (countryIsoCode: string, stateIsoCode: string) | State |
Usage Example:
import { State } from "country-state-city";
const states = State.getStatesOfCountry("US");
console.log("States in US:", states);
// Sample Output:
// [
// {
// name: "California",
// isoCode: "CA",
// countryCode: "US",
// latitude: "36.7783",
// longitude: "-119.4179"
// },
// ...more states
// ]
const state = State.getStateByCodeAndCountry("US", "CA");
console.log("State CA in US:", state);
// Sample Output:
// {
// name: "California",
// isoCode: "CA",
// countryCode: "US",
// latitude: "36.7783",
// longitude: "-119.4179"
// }
City Functions
Function Name | Description | Arguments | Return Type |
---|---|---|---|
getCitiesOfCountry | Returns all cities in a given country | (countryCode: string) | City[] |
getCitiesOfState | Returns all cities in a given state | (countryCode: string, stateCode: string) | City[] |
Usage Example:
import { City } from "country-state-city";
const citiesCountry = City.getCitiesOfCountry("US");
console.log("Cities in US:", citiesCountry);
// Sample Output:
// [
// {
// name: "New York City",
// stateCode: "NY",
// countryCode: "US",
// latitude: "40.7128",
// longitude: "-74.0060"
// },
// ...more cities
// ]
const citiesState = City.getCitiesOfState("US", "CA");
console.log("Cities in CA, US:", citiesState);
// Sample Output:
// [
// {
// name: "Los Angeles",
// stateCode: "CA",
// countryCode: "US",
// latitude: "34.0522",
// longitude: "-118.2437"
// },
// ...more cities
// ]
Additional Helpers (Readers)
Readers are helper functions that extract specific data fields from the raw geographical data.
Example Implementation:
// Extract key fields from a Country object
COUNTRY_READER
// Extract key fields from a State object
STATE_READER
// Extract key fields from a City object
CITY_READER
// For example, to extract time zone info (if available)
TIME_ZONE_READER
Usage Example:
import { COUNTRY_READER, STATE_READER, CITY_READER } from './yourHelpersModule';
import { Country, State, City } from "country-state-city";
const country = Country.getCountryByCode("US");
console.log("Country Data: Name", COUNTRY_READER.name(country));
const state = State.getStateByCodeAndCountry("US", "CA");
console.log("State Data: isoCode", STATE_READER.isoCode(state));
const cities = City.getCitiesOfState("US", "CA");
if (cities.length > 0) {
console.log("City Data: countryCode", CITY_READER.countryCode(cities[0]));
}
License
This project is licensed under the MIT License. See the LICENSE file for details.