Home › Learn › JavaScript › Strings and numbers

Parsing and formatting numbers

Lesson 28 of 40. Text to number, number to text, safely.

Number("42") converts text to a number and gives NaN (not a number) for anything it cannot read; parseInt("42px", 10) reads the leading integer and ignores the rest; parseFloat does the same with decimals. Test for failure with Number.isNaN(x), never x === NaN (NaN is not equal to itself).

Going the other way, x.toFixed(2) gives a string with two decimals, x.toLocaleString("en-US") inserts thousands separators, and Intl.NumberFormat handles currencies: new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(1234.5) is "$1,234.50".

console.log(Number("3.5") + 1);          // 4.5
console.log(Number.isNaN(Number("abc")));  // true
console.log(parseInt("12px", 10));        // 12
console.log((1234.5).toFixed(1));         // "1234.5"

Your task

Write safeNumber(text, fallback) returning the number in the text or the fallback when it is not a valid number (note that empty text should also give the fallback), money(amount) returning "$1,234.50" style text for US dollars, and percent(ratio) returning the ratio as a percentage string with one decimal, so 0.456 gives "45.6%".

Part of the final project. money formats every amount on the receipt as US dollars. It is saved in this browser and loaded into Project: checkout when you get there.

Hint 1

if (text.trim() === "") return fallback; const n = Number(text); return Number.isNaN(n) ? fallback : n;

Hint 2

new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); and (ratio * 100).toFixed(1) + "%"

Show the solution
function safeNumber(text, fallback) {
  if (text.trim() === "") return fallback;
  const n = Number(text);
  return Number.isNaN(n) ? fallback : n;
}

function money(amount) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount);
}

function percent(ratio) {
  return (ratio * 100).toFixed(1) + "%";
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.