Documentation for automated readers
A curated documentation index is available at: https://grafana.com/llms.txt
A complete documentation index is available at: https://grafana.com/llms-full.txt
These indexes can help with page discovery before fetching individual documents.
This page is also available in Markdown, which may be easier for automated readers and AI tools to parse than HTML. The Markdown version is available at https://grafana.com/docs/k6/next/javascript-api/jslib/testing/non-retrying-assertions/tobecloseto.md, or by sending Accept: text/markdown to https://grafana.com/docs/k6/next/javascript-api/jslib/testing/non-retrying-assertions/tobecloseto/. For broader documentation discovery, the curated index is available at https://grafana.com/llms.txt and the complete index is available at https://grafana.com/llms-full.txt.
This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
toBeCloseTo()
The toBeCloseTo() method asserts that a number is close to another number within a specified precision. This is useful for comparing floating-point numbers where exact equality might fail due to precision issues.
Syntax
expect(actual).toBeCloseTo(expected);
expect(actual).toBeCloseTo(expected, precision);
expect(actual).not.toBeCloseTo(expected);
expect(actual).not.toBeCloseTo(expected, precision);Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| expected | number | The expected number | |
| precision | number | 2 | Number of decimal digits to check |
Returns
| Type | Description |
|---|---|
| void | No return value |
Description
The toBeCloseTo() method checks if two numbers are approximately equal within a specified precision. It uses the formula Math.abs(actual - expected) < Math.pow(10, -precision) / 2 to determine if the numbers are close enough.
This is particularly useful when working with floating-point arithmetic where exact equality comparisons might fail due to precision limitations.
Usage
import { expect } from 'https://jslib.k6.io/k6-testing/0.6.1/index.js';
export default function () {
// Floating-point arithmetic precision issues
expect(0.1 + 0.2).toBeCloseTo(0.3);
expect(0.1 + 0.2).toBeCloseTo(0.3, 2);
// These would fail with toBe()
// expect(0.1 + 0.2).toBe(0.3); // This fails!
// More examples
expect(1.005).toBeCloseTo(1, 0);
expect(1.005).toBeCloseTo(1.01, 1);
expect(1.005).not.toBeCloseTo(1.01, 2);
}Was this page helpful?
Related resources from Grafana Labs

