ScreenshotNeo

BlogHow-to

How to Compare Percentage Text and Numbers in Cypress

Compare Cypress percentage text safely by choosing exact-string or numeric assertions, handling 42% versus 0.42, retries, parsing, and failures.

By the ScreenshotNeo team30 September 20265 min read

How to Compare Percentage Text and Numbers in Cypress

Use an exact text assertion when the displayed format is the contract; parse and compare a number when the semantic value is the contract. For 42%, decide whether the expected value is 42 percentage points or 0.42 as a ratio before writing the assertion.

1. Choose the comparison you actually need

Goal Assertion What it verifies
Exact display have.text Percent sign, spacing, decimals and formatting
Leading numeric value parseFloat or Number.parseFloat 42% becomes 42
Strict percentage ratio Validate, remove %, divide by 100 42% becomes 0.42
Eventually updated value .should(callback) Retries until the rendered value satisfies every assertion

2. Assert the exact displayed percentage

Use this when the UI contract says the user must see precisely 42%.

cy.get('[data-testid="completion"]')
  .should('have.text', '42%')

have.text is sensitive to whitespace and formatting. If the page intentionally contains a non-breaking space, include it explicitly:

cy.get('[data-testid="completion"]')
  .should('have.text', '42\u00a0%')

3. Compare percentage points as a number

Cypress can retrieve text, convert it, and apply a numeric assertion. This follows the common Cypress pattern of invoking text and passing the result through parseFloat.

Choose the numeric scale before converting percentage text.
Choose the numeric scale before converting percentage text.
cy.get('[data-testid="completion"]')
  .invoke('text')
  .then((text) => Number.parseFloat(text))
  .should('eq', 42)

parseFloat('42%') reads the leading numeric portion and returns 42. It does not convert the value to 0.42. Use this only when the format is controlled and percentage points are the intended unit.

4. Parse a percentage strictly and normalize it to a ratio

When your application stores the semantic value as a fraction, validate the entire string instead of silently accepting arbitrary leading characters.

const parsePercentAsRatio = (text) => {
  const match = text.trim().match(/^([+-]?\d+(?:\.\d+)?)%$/)
  if (!match) {
    throw new Error(`Expected a percentage, received: ${text}`)
  }
  return Number(match[1]) / 100
}

cy.get('[data-testid="completion"]')
  .invoke('text')
  .then(parsePercentAsRatio)
  .should('eq', 0.42)

Adapt the grammar to your data contract. Decide whether signs, decimal values, surrounding whitespace, values above 100, or locale-specific decimal separators are valid. CSS percentage syntax does not define how your application stores business data.

5. Retry while the UI updates

Values populated by a request, animation, or polling process may not be ready when the element first appears. A callback passed to .should() is retried by Cypress until its assertions pass or the command times out.

cy.get('[data-testid="completion"]')
  .should(($el) => {
    const text = $el.text().trim()
    expect(text).to.match(/^\d+(?:\.\d+)?%$/)
    expect(Number.parseFloat(text)).to.equal(42)
  })

Keep the callback synchronous. Do not call Cypress commands inside it; put commands in the chain and use the callback for assertions against the yielded subject.

6. Compare two rendered values

First decide whether both values use the same unit. The example below compares percentage points after parsing each element.

cy.get('[data-testid="percent-label"]')
  .invoke('text')
  .then((text) => Number.parseFloat(text))
  .then((shown) => {
    cy.get('[data-testid="percent-value"]')
      .invoke('text')
      .then((text) => Number.parseFloat(text))
      .should((other) => {
        expect(other).to.equal(shown)
      })
  })

If one element contains 42% and the other contains 0.42, normalize both to the same scale before comparing.

7. Normalize only irrelevant display noise

Whitespace, case, or formatting should be normalized only when those differences are not part of the product requirement. A small helper keeps that decision visible:

const normalizeText = (value) =>
  value.replace(/\s+/g, ' ').trim().toLowerCase()

cy.get('[data-testid="status"]')
  .invoke('text')
  .then(normalizeText)
  .should('eq', 'complete')

Do not normalize away a percent sign, decimal precision, or a negative sign when those characters carry meaning.

8. Common failures and fixes

Failure Cause Fix
have.text fails although the value looks right Extra whitespace, a non-breaking space, or different decimal formatting Inspect the exact text; assert the intended whitespace explicitly or normalize only irrelevant spacing
Expected 0.42, received 42 parseFloat returns percentage points Remove the suffix with a strict parser and divide by 100
Parser accepts malformed text Leading-number parsing ignores the rest of the string Validate the complete value with an anchored regular expression
Assertion runs before the final value appears Asynchronous rendering Use a retryable .should(callback) and assert the final format and value together
Callback behaves unpredictably Cypress commands were called inside the callback Move commands outside; keep the callback synchronous
Negative assertion passes unexpectedly The element may be temporarily absent or in an unrelated state Assert the desired positive value or state directly
Locale decimal format fails The parser expects a dot but the UI uses a comma Define locale handling explicitly before conversion

9. Performance, reliability and maintainability

  • Prefer stable selectors: use data-testid or another contract owned by the component rather than layout classes.
  • Make units obvious: name helpers and expected values for their scale, such as expectedPercentagePoints or expectedRatio.
  • Keep parsing deterministic: avoid locale-dependent implicit conversions and document accepted formats.
  • Retry the smallest useful subject: query the percentage element directly so Cypress does not wait on an unnecessarily broad region.
  • Use positive assertions: a positive value assertion proves the intended state more reliably than only checking that an incorrect state is absent.
  • Control floating-point expectations: for computed ratios, use an appropriate tolerance when binary floating-point rounding is possible.

10. Capture a reproducible result with ScreenshotNeo

If a failing Cypress run needs a visual artifact, you can capture the page from a URL with ScreenshotNeo. It provides PNG, JPEG, WebP or PDF output and can wait for a selector, delay or network idle, which helps preserve the rendered percentage state.

A clean capture preserves the page state you want to inspect.
A clean capture preserves the page state you want to inspect.

Or skip the browser setup

Call the API directly:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for options. Cookie banners, newsletter popups and chat widgets are removed before capture; bot checks, blank pages and failed loads are never billed. An MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 shots. Start with a free ScreenshotNeo account.

11. FAQ

Should I use have.text or parse the value?

Use have.text when presentation is part of the contract. Parse when the test is about numeric meaning.

Does parseFloat('42%') return 0.42?

No. It returns 42; divide by 100 only when your expected unit is a ratio.

Can Cypress retry a text-to-number conversion?

Yes. Put the conversion and assertions in a .should(callback) callback so Cypress retries them while the element updates.

Should values over 100 percent be rejected?

Only if your product contract forbids them. The parser should enforce the application’s domain rules rather than assuming a universal range.