Day 9: Strings, Numbers, Money & Dates
✅ 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
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);| Method | Example → 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) → "⭐⭐⭐⭐" |
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
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);
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
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));Rupee formatting with Intl
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));Dates: delivery slots, age, countdowns
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'));| Need | Use |
|---|---|
| Now | new Date() / Date.now() (milliseconds) |
| Parse safely | ISO strings: "2026-10-25T10:30:00+05:30" |
| Parts | getFullYear, getMonth (0 = Jan!), getDate, getDay (0 = Sun) |
| Add days | d.setDate(d.getDate() + n) |
| Difference | (date2 - date1) / 86 400 000 = days |
| Show to users | Intl.DateTimeFormat with locale and timeZone |
Real task: Diwali sale countdown
<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>🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
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 '));Show solution
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);Quick quiz
🧠 Quick Quiz – test yourself
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.
Day 10: the DOM – select elements and change text, classes, styles and attributes on a real page.
