0.0.13 • Published 4 months ago

@verzonix/conversion v0.0.13

Weekly downloads
-
License
-
Repository
-
Last release
4 months ago

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, and en-IN.
The locale is determined by: 1. navigator.language 2. A local storage key: LOCALIZATION_STORAGE_KEY 3. A language prop passed to the ConversionProvider

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 NameDescriptionArgumentsReturn Type
getFormattedNumberFormats a number as a string(value: number, options?: FormatNumberExtraParams)string
getParsedFormattedNumberParses a formatted number string back to a number(value: string, options?: FormatNumberExtraParams)number

FormatNumberExtraParams

OptionTypeDefaultDescription
decimalPlacesnumber2Number of decimal places to show
useGroupingbooleantrueWhether to use grouping separators (e.g., thousands separators)
languageLOCALIZED_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 NameDescriptionArgumentsReturn Type
getFormattedPercentageFormats a number as a percentage string(value: number, options?: FormatPercentageOptions)string
getParsedPercentageParses a formatted percentage string back to a number(value: string, options?: FormatPercentageOptions)number

FormatPercentageOptions

OptionTypeDefaultDescription
decimalPlacesnumber2Number of decimal places to show
useGroupingbooleantrueWhether to use grouping separators
languageLOCALIZED_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 NameDescriptionArgumentsReturn Type
getFormattedCurrencyFormats a number as a currency string(value: number, options?: FormatCurrencyExtraParams)string
getParsedFormattedCurrencyParses a formatted currency string back to a number(value: string, options?: FormatCurrencyExtraParams)number
getCurrencySymbolGets the currency symbol for the current localeNonestring

FormatCurrencyExtraParams

OptionTypeDefaultDescription
decimalPlacesnumber2Number of decimal places to show
useGroupingbooleantrueWhether to use grouping separators
languageLOCALIZED_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 NameDescriptionArgumentsReturn Type
getFormattedDateAndTimeFormats a date and time(date: Date, options?: FormatDateAndTimeExtraParams)string
getInputFormattedDateAndTimeFormats a date string based on locale(dateString: string, options?: Omit<FormatDateAndTimeExtraParams, 'language'>)number
getTimeStampFromDateStringGets a timestamp from a date string(dateString: string)number
getStartofCurrentDayGets the timestamp for the start of the current dayNoneTimestamp
getEndofCurrentDayGets the timestamp for the end of the current dayNoneTimestamp
getStartofCurrentWeekGets the timestamp for the start of the current weekNoneTimestamp
getEndofCurrentWeekGets the timestamp for the end of the current weekNoneTimestamp
getStartofCurrentMonthGets the timestamp for the start of the current monthNoneTimestamp
getEndofCurrentMonthGets the timestamp for the end of the current monthNoneTimestamp
getStartofCurrentQuarterGets the timestamp for the start of the current quarterNoneTimestamp
getEndofCurrentQuarterGets the timestamp for the end of the current quarterNoneTimestamp
getStartofCurrentYearGets the timestamp for the start of the current yearNoneTimestamp
getEndofCurrentYearGets the timestamp for the end of the current yearNoneTimestamp
getStartofLastNDaysFromTodayGets the timestamp for the start of the last N days from today(days: number)Timestamp
getEndofLastNDaysFromTodayGets the timestamp for the end of the last N days from today(days: number)Timestamp

FormatDateAndTimeExtraParams

OptionTypeDefaultDescription
showDatebooleantrueWhether to display the date
showTimeboolean-Whether to display the time
is12Hourboolean-Use 12-hour time format
showMonthboolean-Whether to display the month
showYearboolean-Whether to display the year
showSecondsboolean-Whether to display seconds
dayFormatDAY_FORMAT (enum)-Format for the day (e.g., numeric, long)
monthFormatMONTH_FORMAT (enum)-Format for the month (e.g., numeric, long)
yearFormatYEAR_FORMAT (enum)-Format for the year
hourFormatHOUR_FORMAT (enum)-Format for the hour
minuteFormatMINUTE_FORMAT (enum)-Format for minutes
secondFormatSECOND_FORMAT (enum)-Format for seconds
representationFormatREPRESENTATION_FORMAT (enum)-Overall representation format
timeZonestring-Time zone to use for formatting
languageLOCALIZED_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 NameDescriptionArgumentsReturn Type
getFormattedPhoneNumberFormats a phone number(phoneNumber: string, options?: FormatPhoneNumberOptions){ countryCode: string; phoneNumber: string }
isValidPhoneNumberChecks if the phone number is valid(phoneNumber: string, options?: FormatPhoneNumberOptions)boolean
getFormattedInputPhoneNumberFormats a phone number for input fields(phoneNumber: string, options?: FormatPhoneNumberOptions)string
getParsedPhoneNumberParses a formatted phone number(phoneNumber: string, options?: FormatPhoneNumberOptions){ countryCode: string; phoneNumber: string }
getDefaultCountryCodeReturns the default country codeNonestring

FormatPhoneNumberOptions

OptionTypeDefaultDescription
formatTypePHONE_NUMBER_FORMAT_TYPEPHONE_NUMBER_FORMAT_TYPE.INTERNATIONALFormat type for the phone number
languageLOCALIZED_CONVERSION_LANGUAGES-Language used for formatting
typeFORMAT_PHONE_NUMBER_TYPE-Specific phone number format type
regionstring-Region information for formatting
countryCodestring | number-Country code to use for the phone number

ParsedPhoneNumber Structure

PropertyTypeDescription
countryCodestringThe country code of the phone number
nationalNumberstringThe national number part of the phone number
extensionstring | undefinedThe extension of the phone number (if any)
regionCodestringThe 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 NameDescriptionArgumentsReturn Type
getAllCountriesReturns all countriesNoneCountry[]
getCountryByCodeReturns 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 NameDescriptionArgumentsReturn Type
getStatesOfCountryReturns all states of a given country(countryIsoCode: string)State[]
getStateByCodeAndCountryReturns 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 NameDescriptionArgumentsReturn Type
getCitiesOfCountryReturns all cities in a given country(countryCode: string)City[]
getCitiesOfStateReturns 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.

0.0.10

4 months ago

0.0.11

4 months ago

0.0.12

4 months ago

0.0.13

4 months ago

0.0.6

5 months ago

0.0.5

5 months ago

0.0.4

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago