Code  JS

Code JS


Convert Number to Currency Format Using JavaScript

In this video, you will learn how to format numbers into any country’s localized format using the Intl.NumberFormat object which enables language-sensitive number formatting.





What is GEEK

Buddha Community

Convert Number to Currency Format Using JavaScript
Chloe  Butler

Chloe Butler


Pdf2gerb: Perl Script Converts PDF Files to Gerber format


Perl script converts PDF files to Gerber format

Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.

The general workflow is as follows:

  1. Design the PCB using your favorite CAD or drawing software.
  2. Print the top and bottom copper and top silk screen layers to a PDF file.
  3. Run Pdf2Gerb on the PDFs to create Gerber and Excellon files.
  4. Use a Gerber viewer to double-check the output against the original PCB design.
  5. Make adjustments as needed.
  6. Submit the files to a PCB manufacturer.

Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).

See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.

#Pdf2Gerb config settings:
#Put this file in same folder/directory as itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;

use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)

#configurable settings:
#change values here instead of in main file

use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call

#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)} ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software.  \nGerber files MAY CONTAIN ERRORS.  Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG

use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC

use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)

#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1); 

#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
#round or square pads (> 0) and drills (< 0):
    .010, -.001,  #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
    .031, -.014,  #used for vias
    .041, -.020,  #smallest non-filled plated hole
    .051, -.025,
    .056, -.029,  #useful for IC pins
    .070, -.033,
    .075, -.040,  #heavier leads
#    .090, -.043,  #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
    .100, -.046,
    .115, -.052,
    .130, -.061,
    .140, -.067,
    .150, -.079,
    .175, -.088,
    .190, -.093,
    .200, -.100,
    .220, -.110,
    .160, -.125,  #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
    .090, -.040,  #want a .090 pad option, but use dummy hole size
    .065, -.040, #.065 x .065 rect pad
    .035, -.040, #.035 x .065 rect pad
    .001,  #too thin for real traces; use only for board outlines
    .006,  #minimum real trace width; mainly used for text
    .008,  #mainly used for mid-sized text, not traces
    .010,  #minimum recommended trace width for low-current signals
    .015,  #moderate low-voltage current
    .020,  #heavier trace for power, ground (even if a lighter one is adequate)
    .030,  #heavy-current traces; be careful with these ones!
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);

#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size:   parsed PDF diameter:      error:
#  .014                .016                +.002
#  .020                .02267              +.00267
#  .025                .026                +.001
#  .029                .03167              +.00267
#  .033                .036                +.003
#  .040                .04267              +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
    HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
    RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
    SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
    RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
    TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
    REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects

#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
    CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
    CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
    SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
    WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
    RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found

#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches

#line join/cap styles:
use constant
    CAP_NONE => 0, #butt (none); line is exact length
    CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
    CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
    CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
#number of elements in each shape type:
use constant
    RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
    LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
    CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
    CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
    rect => RECT_SHAPELEN,
    line => LINE_SHAPELEN,
    curve => CURVE_SHAPELEN,
    circle => CIRCLE_SHAPELEN,

#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions

# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?

#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes. 
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes

#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches

# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)

# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time

# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const

use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool

my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time

print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load


#use Package::Constants;
#use Exporter qw(import); #

#my $caller = "pdf2gerb::";

#sub cfg
#    my $proto = shift;
#    my $class = ref($proto) || $proto;
#    my $settings =
#    {
#        $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
#    };
#    bless($settings, $class);
#    return $settings;

#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;

#print STDERR "read cfg file\n";

#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #; NOTE: "_OK" skips short/common names

#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }

Download Details:

Author: swannman
Source Code:

License: GPL-3.0 license


Format a Number as Currency in JavaScript

Format a Number as Currency in JavaScript

When you're working with data from an API or an external resource, you'll get these data in some general format. For example, if you are building a store, you might have data like price.

This price data might be in the form of a general number such as 14340 or any other number as seen in the array below:

const books = [
        "id": 001,
        "name": "Clean Code",
        "price": 10.99,
        "id": 002,
        "name": "Introduction to Algorithms",
        "price": 1199,
        "id": 003,
        "name": "Programming Pearls",
        "price": 1.05,
        "id": 004,
        "name": "Program or Be Programmed",
        "price": 14340,

You don't want to pass in numbers directly into your application or web page because they'll be difficult for the readers and users to understand.

Even if you add a currency sign, it doesn’t fix the problem because you would want to add commas and decimals in the correct positions. You’d also want each price output based on the currency with proper formatting.

For example, 14340 would be $14,340.00 (US Dollars) or ₹14,340.00 (Rupees) or €14.340,00 (Euross) and so on, depending on your defined currency, locale, and style. And you can convert these numbers into currencies using the Intl.NumberFormat() method in JavaScript.

In case you are in a rush, here is a basic example of what the code will look like:

const price = 14340;

// Format the price above to USD using the locale, style, and currency.
let USDollar = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',

console.log(`The formated version of ${price} is ${USDollar.format(price)}`);
// The formated version of 14340 is $14,340.00

In this article, I'll help you understand each of the above options, what they do, and how to properly use this method to format a number as currency.

How to Use the Intl.NumberFormat() Constructor to Format Numbers as Currency

You can use the Intl.NumberFormat() constructor to create Intl.NumberFormat objects that enable language-sensitive number formatting, such as currency formatting.

This constructor takes in two major parameters, locales and options. They're both optional.

new Intl.NumberFormat(locales, options)

// Or

Intl.NumberFormat(locales, options)

Note that Intl.NumberFormat() can be called with or without new. Both will create a new Intl.NumberFormat instance.

When you use the Intl.NumberFormat() constructor without passing any locale or option, it will only format the number by adding commas.

const price = 14340;
console.log(new Intl.NumberFormat().format(price)); // 14,340

You are not after regular number formatting, as seen above. You want to format these numbers as currency – so it returns the currency symbol with proper formatting without having to concatenate manually.

Let’s now explore both parameters.

The First Argument: Locales

The locale is an optional parameter that can be passed as a string. It represents a specific geographical, political, or cultural region. It just formats the number based on the locale and is not the currency formatting.

const price = 143450;

console.log(new Intl.NumberFormat('en-US').format(price)); // 143,450
console.log(new Intl.NumberFormat('en-IN').format(price)); // 1,43,450
console.log(new Intl.NumberFormat('en-DE').format(price)); // 143.450

You will notice that the numbers or prices are now formatted locally based on the locale. Let’s now explore the options parameter to customize the numbers as a currency.

The Second Argument: Options (Style, Currency, …)

This is the main parameter and you can use it to apply more formatting like that of currency. This is a JavaScript object that holds other parameters like:

  • style: You use this to specify the type of formatting you want. This takes in values like decimals, currency, and units. For this article, you will use currency because that is the style in which you want to format the number.
  • currency: Another option is currency. You can use this option to specify the currency you want to format to, such as 'USD', 'CAD', 'GBP``', 'INR' and lots more. This will also help provide the symbol in the appropriate position based on the locale.
// format number to US dollar
let USDollar = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',

// format number to British pounds
let pounds = Intl.NumberFormat('en-GB', {
    style: 'currency',
    currency: 'GBP',

// format number to Indian rupee
let rupee = new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',

// format number to Euro
let euro = Intl.NumberFormat('en-DE', {
    style: 'currency',
    currency: 'EUR',

console.log('Dollars: ' + USDollar.format(price));
// Dollars: $143,450.00

console.log(`Pounds: ${pounds.format(price)}`);
// Pounds: £143,450.00

console.log('Rupees: ' + rupee.format(price));
// Rupees: ₹1,43,450.00

console.log(`Euro: ${euro.format(price)}`);
// Euro: €143,450.00

There are other options you’ll most likely never use or change, such as useGrouping, which is used to group the number using commas (or periods, for some locales). This is a boolean field – by default, it is set to true. This is why your output has had a comma or period in this article (like $143,450.00).

When you set its value to false, you will notice there is no more grouping:

let euro = Intl.NumberFormat('en-DE', {
    style: 'currency',
    currency: 'EUR',
    useGrouping: false,

console.log(`Euro: ${euro.format(price)}`);
// Euro: €143450.00

Another option is the maximumSignificantDigits. You can use this to round your price variable based on the number of significant digits you have set. For example, when you set the value to 3, 143,450.00 will become 143,000.

let pounds = Intl.NumberFormat('en-GB', {
    style: 'currency',
    currency: 'GBP',
    maximumSignificantDigits: 3,

console.log(`Pounds: ${pounds.format(price)}`);
// Pounds: £143,000

Voilà! 🚀

I hope this article was worth your time. You now know how to format a number as currency with JavaScript without relying on any external library.

When working with libraries like React, Vue, and others, you can make this a utility function, import it into any of your components, and use it instead of installing an entire library (unless you need more functionalities).

Have fun coding!

Original article source at:

#javascript #number #currency 

CSS Boss

CSS Boss


How to create a calculator using javascript - Pure JS tutorials |Web Tutorials

In this video I will tell you How to create a calculator using javascript very easily.

#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html

How to Convert Base 2 Binary Number String To integer In Python

In this pythonn tutorial we will learn about how to convert base 2 binary number string to integer in Python. Ever faced the challenge of converting a binary number string into an integer for smooth processing in your Python code? Python offers seamless solutions for transforming data types without a hitch, making it an ideal choice for developers worldwide.

In this article, we’ll delve into two popular methods to tackle binary string conversion: Python’s built-in int() function and the powerful bitstring library, part of the bit array package. Join us as we break down each approach, guiding you through the process of efficient typecasting in Python.

What Is A Base-2 Number String?

A binary number is expressed in the base-2 number system using only “0”s and “1”s. The zeros and ones are called the index of a binary number. They are also called “bits”.

A computer system only uses the binary system for computations. It is the way in which machine code is written. Circuit diagrams can be used to represent the working of binary systems.

Boolean algebra including “AND”, “OR” and “NOT” gates can be used to represent addition, subtraction, multiplications in the binary system.

We can easily convert a number that is an integer from the decimal system, that is the base-10 system to the binary system by dividing it with 2 and arranging the remainders in a bottom-to-top order.

From Decimal To Base 2 Conversion

Converting Decimal to Base-2 Numbers

A binary number can also be converted easily into a decimal number in mathematics.


Converting a Base-2 Number String to an Integer in Python

A string in python is something that is written between two quotation marks, for example, “this is a string”.

Hence, a base-2 number string is a binary number written between two quotation marks . For example-‘1010001’ is a base-2 number string.

Advantages of Explicit Typecasting in Python

In python, programmers can clearly define the conversion of one data type into another in their code. This is known as explicit typecasting in python.

Explicit typecasting is extremely useful. Unlike other programming languages, python has built-in functions that can perform explicit typecasting without having to write huge blocks of code for transforming one data type into another.

Explicit typecasting has many advantages. Some of them are:

  • It helps in converting lower data types into higher ones for ease of operations.
  • It prevents the loss of data when converting from one data type to another.
  • Functions like int() and str() are extremely helpful and hassle free to use.

Method 1: Converting Base-2 Number String to Integer Using int() Function

We can use the int() built-in function to convert a string literal into an integer in python. Let’s look at how we can implement this :

#converting a base-2 number string into an integer.
#taking an input for a number in the form of a string
inin=input("Enter a binary number= ")
#displaying the input
print("The given input is=",inin)
#converting using int()
#displaying the output
print("the number in the decimal system or as an integer is=",outout)

The output would be:

Enter a binary number= 10011
The given input is= 10011
the number in the decimal system or as an integer is= 19

Using The Int Function

Example: Converting Binary String with int() Function

Method 2: Converting Base-2 Number String to Integer Using BitString Library

The bitstring module helps in natural and easy creation of binary data. Binary data analysis and manipulation using bitstring comes in very handy along with the BitArray class.

Before we can use this module we have to install in it our system, run the following code in your command prompt:

pip install bitstring

Let’s see how we can implement this:

#converting a base-2 number string into an integer.
#importing required modules
from bitstring import BitArray
#taking an input for a number in the form of a string
inin=input("Enter a binary number= ")
#displaying the input
print("The given input is=",inin)
#converting using bitArray
#displaying the output
print("the number in the decimal system or as an integer is=",outout)

The output will be:

Enter a binary number= 0100111
The given input is= 0100111
the number in the decimal system or as an integer is= 39

Using The Bitstring Module

Example: Converting Binary String with Bitstring Module


Throughout this tutorial, we’ve explored the process of converting binary numbers to decimal integers in Python. With Python’s extensive library of built-in functions and modules, there’s no need for manual calculations. Explicit typecasting is a powerful feature that simplifies this conversion process. We have demonstrated two methods for converting base-2 number strings to integers: using the int() function and the bitstring module.

Article source at:


Sheldon  Grant

Sheldon Grant


How to Convert Numbers to Ordinals in JavaScript

In this tutorial, you’ll learn how to convert numbers to ordinals in JavaScript. Getting the ordinal of a number allows you to display it in a human-readable format.

What Are Ordinals?

Ordinals define numbers as being part of an order or sequence. The words “first”, “second”, and “third” are all examples of ordinals. When using numbers to display chart results, days of the month, or a ranking, you’ll often need to use ordinals.

Numbers can be used to display many different types of data and results. When numbers are presented to users, they often need be presented in a format that’s more readable — such as adding ordinal suffix (“June 12th” rather than “June 12”, for example).

Ordinal Suffix Rules in English

Let’s take a look at how ordinals are used in the English language. English ordinals follow a predictable, if not beautifully simple, set of rules:

“st” is appended to 1 and numbers that are one greater than a multiple of ten, except for 11 and numbers that are 11 greater than a multiple of 100. For example, 1st, 21st, 31st, etc. … but 11th, 111th, etc.

“nd” is appended to 2 and numbers that are two greater than a multiple of ten, except for 12 and numbers that are 12 greater than a multiple of 100. For example, 2nd, 22nd, 32nd, etc. … but 12th, 112th, etc.

“rd” is appended to 3 and numbers that are three greater than a multiple of ten, except for 13 and numbers that are 13 greater than a multiple of 100. For example, 3rd, 23rd, 33rd, etc. … but 13th, 113th, etc.

“th” is appended to everything else. For example, 24th.

How to Get the Ordinal of a Number

To get the ordinal of a number, you can use the following function:

function getOrdinal(n) {
  let ord = 'th';

  if (n % 10 == 1 && n % 100 != 11)
    ord = 'st';
  else if (n % 10 == 2 && n % 100 != 12)
    ord = 'nd';
  else if (n % 10 == 3 && n % 100 != 13)
    ord = 'rd';

  return ord;

The function getOrdinal accepts an argument that is a number and returns the ordinal of that number. Since most ordinals end in “th”, the default value of ord is set to th. Then, you test the number on different conditions and change the ordinal if necessary.

You’ll notice that in each of the conditions the remainder (%) operator is used. This operator returns the leftover value of dividing the left operand by the right operand. For example, 112 % 100 returns 12.

To test if the number should have the ordinal st, you check if n is one greater than a multiple of ten (n % 10 == 1, which includes 1 itself), but isn’t 11 greater than a multiple of 100 (n % 100 != 11, which includes 11 itself).

To test if the number should have the ordinal nd, you check if n is 2 greater than a multiple of ten (n % 10 == 2 which includes 2 itself), but isn’t 12 greater than a multiple of 100 (n % 100 != 12, which includes 12 itself).

To test if the number should have the ordinal rd, you check if n is 3 greater than a multiple of ten (n % 10 == 3, which includes 3 itself), but isn’t 13 greater than a multiple of 100 (n % 100 != 13, which includes 13 itself).

If all of the conditions are false, then the value of ord remains th.

You can test it in live action with the following CodePen demo.


In this tutorial, you’ve learned how to retrieve the ordinal of a number. Ordinals can be used in variety of cases, such as displaying dates or ranking in human-readable formats.

Original article source at:

#javascript #convert #numbers