Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🖱️ Days 8–14 – Data, DOM & Events  ·  Day 09

Day 9: Strings, Numbers, Money & Dates

⏱ 95 min📶 Intermediate🎯 100% self-study
Day 9 / 30

✅ Today you will learn

  • String methods for cleaning and formatting user input
  • Math, rounding and random numbers
  • Money without floating-point bugs (work in paise)
  • Intl.NumberFormat for ₹ and lakh/crore formatting
  • Dates: creating, formatting, adding days, differences

🏢 In the real world

Three real complaints from a billing app: names saved as “ aarti GUPTA ”, a bill of ₹0.1 + ₹0.2 showing ₹0.30000000000000004, and delivery dates shown as “Sat Oct 25 2026 10:30:00 GMT+0530”. All three are fixed with the built-in String, Number, Intl and Date tools you learn today.

Cleaning and formatting strings

JavaScript
const raw = '  aarti GUPTA ';
const clean = raw.trim().toLowerCase().split(' ').filter(Boolean)
  .map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
console.log(`"${clean}"`);

const phone = '+91 98290-12345';
const digits = phone.replace(/\D/g, '').slice(-10);     // keep the last 10 digits
console.log(digits, digits.length === 10);

const masked = digits.slice(0, 2) + '******' + digits.slice(-2);
console.log('OTP sent to', masked);

const invoiceNo = String(42).padStart(5, '0');
console.log(`INV-${invoiceNo}`);
console.log('Kaju Katli'.includes('Katli'), 'ghewar'.startsWith('ghe'), 'menu.pdf'.endsWith('.pdf'));
console.log('a-b-c'.replaceAll('-', ' / '), 'Ladoo'.at(-1), 'Rasmalai'.length);
"Aarti Gupta" 9829012345 true OTP sent to 98******45 INV-00042 true true true a / b / c o 8
MethodExample → result
trim()" hi " → "hi"
toUpperCase / toLowerCase"Ghewar" → "GHEWAR"
includes / startsWith / endsWith"kaju".includes("aj") → true
slice(a, b)"Jaipur".slice(0, 3) → "Jai"
split(sep) / join"a,b".split(",") → ["a","b"]
replace / replaceAll"1-2-3".replaceAll("-", "") → "123"
padStart / padEnd"7".padStart(3, "0") → "007"
repeat"⭐".repeat(4) → "⭐⭐⭐⭐"
🧠 Strings never change

Every string method returns a NEW string; the original stays the same. Writing name.trim(); alone does nothing – you must store the result: name = name.trim();.

Numbers and Math

JavaScript
console.log(Math.round(4.5), Math.floor(4.9), Math.ceil(4.1), Math.trunc(-4.7));
console.log(Math.max(380, 900, 650), Math.min(...[380, 900, 650]));
console.log(Math.abs(-250), Math.sqrt(144), Math.PI.toFixed(4));

const r = Math.round(1234.567 * 100) / 100;   // round to 2 decimals as a NUMBER
console.log(r, (1234.567).toFixed(2), typeof (1234.567).toFixed(2));   // toFixed returns a STRING

const otp = Math.floor(100000 + Math.random() * 900000);   // 6-digit OTP (demo only!)
console.log(String(otp).length);
console.log(Number.isInteger(5.0), Number.isFinite(1 / 0), Number.MAX_SAFE_INTEGER);
5 4 5 -4 900 380 250 12 3.1416 1234.57 1234.57 string 6 true false 9007199254740991
⚠️ Math.random is not secure

Never generate real OTPs, passwords or coupon codes with Math.random. Use crypto.getRandomValues() in browsers (or generate them on the server).

Money: the 0.1 + 0.2 problem

JavaScript
console.log(0.1 + 0.2);                       // 0.30000000000000004 ❌
console.log(0.1 + 0.2 === 0.3);

// ✅ Store money as integer paise, convert only for display
const itemsPaise = [45050, 32075, 9990];      // ₹450.50, ₹320.75, ₹99.90
const subtotal = itemsPaise.reduce((s, p) => s + p, 0);
const gst = Math.round(subtotal * 5 / 100);   // round once, at the end
const total = subtotal + gst;
console.log(subtotal, gst, total);
console.log('Pay ₹' + (total / 100).toFixed(2));
0.30000000000000004 false 87115 4356 91471 Pay ₹914.71

Rupee formatting with Intl

JavaScript
const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
console.log(inr.format(1234567.5));
console.log(new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(48200));
console.log(new Intl.NumberFormat('hi-IN', { style: 'currency', currency: 'INR' }).format(9999));
console.log(new Intl.NumberFormat('en-IN', { notation: 'compact' }).format(2500000));
console.log((1234567).toLocaleString('en-IN'));
console.log(new Intl.NumberFormat('en-IN', { style: 'percent', maximumFractionDigits: 1 }).format(0.1234));
₹12,34,567.50 ₹48,200 ₹9,999.00 25L 12,34,567 12.3%

Dates: delivery slots, age, countdowns

JavaScript
const order = new Date('2026-10-25T10:30:00+05:30');   // ISO format = safe to parse
const delivery = new Date(order);
delivery.setDate(delivery.getDate() + 3);                // add 3 days

const fmt = new Intl.DateTimeFormat('en-IN', { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric', timeZone: 'Asia/Kolkata' });
console.log('Ordered:', fmt.format(order));
console.log('Delivery by:', fmt.format(delivery));
console.log(new Intl.DateTimeFormat('hi-IN', { dateStyle: 'full', timeZone: 'Asia/Kolkata' }).format(delivery));

const diwali = new Date('2026-11-08T00:00:00+05:30');
const daysLeft = Math.ceil((diwali - order) / (1000 * 60 * 60 * 24));
console.log(`${daysLeft} days to Diwali 🪔`);

function age(dobIso, onIso) {
  const dob = new Date(dobIso), on = new Date(onIso);
  let years = on.getFullYear() - dob.getFullYear();
  const birthdayPassed = on.getMonth() > dob.getMonth() || (on.getMonth() === dob.getMonth() && on.getDate() >= dob.getDate());
  return birthdayPassed ? years : years - 1;
}
console.log('Age:', age('2008-12-15', '2026-10-25'));
Ordered: Sun, 25 Oct, 2026 Delivery by: Wed, 28 Oct, 2026 बुधवार, 28 अक्टूबर 2026 14 days to Diwali 🪔 Age: 17
NeedUse
Nownew Date() / Date.now() (milliseconds)
Parse safelyISO strings: "2026-10-25T10:30:00+05:30"
PartsgetFullYear, getMonth (0 = Jan!), getDate, getDay (0 = Sun)
Add daysd.setDate(d.getDate() + n)
Difference(date2 - date1) / 86 400 000 = days
Show to usersIntl.DateTimeFormat with locale and timeZone

Real task: Diwali sale countdown

HTML + JavaScript
<p style="font-size:1.3rem">🪔 Diwali sale ends in <b id="left"></b></p>

<script>
const end = new Date();
end.setDate(end.getDate() + 2);          // demo: always 2 days from now
end.setHours(23, 59, 59, 0);

function tick() {
  let ms = Math.max(0, end - new Date());
  const d = Math.floor(ms / 86400000); ms %= 86400000;
  const h = Math.floor(ms / 3600000); ms %= 3600000;
  const m = Math.floor(ms / 60000);
  const s = Math.floor((ms % 60000) / 1000);
  const two = n => String(n).padStart(2, '0');
  document.querySelector('#left').textContent = `${d}d ${two(h)}h ${two(m)}m ${two(s)}s`;
}
tick();
setInterval(tick, 1000);
</script>
▶  Date arithmetic + padStart, updated every second

🏅 Job skills unlocked today

✔ Clean and format text input✔ Round and calculate with Math safely✔ Handle money in paise and format rupees with Intl✔ Create, add to, compare and display dates

Practice tasks

🏋️ Practice – do it yourself

Task 1: Write slugify(title) that turns "Kaju Katli – 1 Kg Box!" into "kaju-katli-1-kg-box".
Show solution
JavaScript
function slugify(title) {
  return title.toLowerCase().trim()
    .replace(/[^a-z0-9]+/g, '-')     // anything that is not a letter/digit → -
    .replace(/^-+|-+$/g, '');        // remove - at the start/end
}
console.log(slugify('Kaju Katli – 1 Kg Box!'));
console.log(slugify('  Diwali Offer 2026  '));
kaju-katli-1-kg-box diwali-offer-2026
Task 2: Split a restaurant bill of ₹2,345.50 among 4 friends in paise so the shares add up exactly (some pay 1 paisa more).
Show solution
JavaScript
const totalPaise = 234550, people = 4;
const base = Math.floor(totalPaise / people);
const extra = totalPaise % people;
const shares = Array.from({ length: people }, (_, i) => base + (i < extra ? 1 : 0));
console.log(shares.map(p => '₹' + (p / 100).toFixed(2)).join(', '));
console.log('Check:', shares.reduce((s, p) => s + p, 0) === totalPaise);
₹586.38, ₹586.38, ₹586.37, ₹586.37 Check: true
Task 3: Show today’s date in English and Hindi using Intl.DateTimeFormat with dateStyle: "full".

Quick quiz

🧠 Quick Quiz – test yourself

1. ' ab '.trim().length is…
Spaces removed.
2. (2.567).toFixed(2) returns…
Use for display.
3. Best way to store ₹450.50 for calculations?
Integers avoid float errors.
4. new Date().getMonth() for October returns…
Months start at 0.
5. Indian grouping 12,34,567 comes from…
Or Intl.NumberFormat.

Interview corner

💼 Interview Corner

Why is 0.1 + 0.2 !== 0.3 and how do you handle money?

Numbers are IEEE-754 binary floating point and cannot represent 0.1 exactly, so tiny errors appear. For money use integer minor units (paise), round once at defined points, or a decimal library; compare floats with a tolerance (Number.EPSILON).

How do you handle time zones in a web app?

Store and send dates in UTC (ISO strings or timestamps), convert only for display with Intl.DateTimeFormat and the user’s or business’s timeZone (e.g. Asia/Kolkata), and avoid parsing ambiguous formats like "25/10/2026".

Summary

  • String methods return new strings: trim, slice, replace, split, padStart.
  • Math.round/floor/ceil; toFixed returns a string for display.
  • Money in paise; Intl.NumberFormat("en-IN", { currency: "INR" }) for display.
  • Dates: ISO input, setDate for adding, Intl.DateTimeFormat for output.
➡️ Next

Day 10: the DOM – select elements and change text, classes, styles and attributes on a real page.

Frequently Asked Questions

Should I use a date library?
For simple apps, Date + Intl are enough. For heavy scheduling use date-fns or the upcoming Temporal API.
Why did we use a regular expression in replace?
Patterns like /\D/g (“every non-digit”) are regular expressions – Day 23 teaches them for real validation.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 10: The DOM: Select and Change the Page Your progress: 9 / 30 (30%) · Lesson 10 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free