Skip to content

Instantly share code, notes, and snippets.

@loclv
Last active April 9, 2024 20:59
Show Gist options
  • Select an option

  • Save loclv/6fa230300c5c8220a6e481bccf1b039f to your computer and use it in GitHub Desktop.

Select an option

Save loclv/6fa230300c5c8220a6e481bccf1b039f to your computer and use it in GitHub Desktop.
bun test round function with Number.EPSILON
import { expect, test } from 'bun:test'
/**
* @example
* round(1.255784, 4)
* returns 1.2558
*
* @param value - the value to be rounded
* @param decimals - the number of decimal places
* @returns - the rounded value
*/
export const round = (value: number, decimals: number) => {
const rounder = 10 ** decimals
return Math.round((value + Number.EPSILON) * rounder) / rounder
}
/**
* Run:
* `bun test ./test.ts`
*/
test('round to 4 decimal place, higher', () => {
expect(round(1.255784, 4)).toBe(1.2558)
})
test('round to 1 decimal place, higher', () => {
expect(round(0.35, 1)).toBe(0.4)
})
test('round 0.355 to 1 decimal place, higher', () => {
expect(round(0.355, 1)).toBe(0.4)
})
test('round to 1 decimal place, lower', () => {
expect(round(0.34, 1)).toBe(0.3)
})
/**
* {@link https://stackoverflow.com/questions/20701029/rounding-issue-in-math-round-tofixed}
*/
test('round to 2 decimal place, higher', () => {
expect(round(239.525, 2)).toBe(239.53)
})
/**
* {@link https://stackoverflow.com/questions/20701029/rounding-issue-in-math-round-tofixed}
*/
test('round 239.575 to 2 decimal place, higher', () => {
expect(round(239.575, 2)).toBe(239.58)
})
export const roundToPlacesWithMath = (value: number, decimals: number) => {
const rounder = 10 ** decimals
return Math.round(value * rounder) / rounder
}
test('roundToPlacesWithMath to 4 decimal place, higher', () => {
expect(roundToPlacesWithMath(1.255784, 4)).toBe(1.2558)
})
test('roundToPlacesWithMath to 1 decimal place, higher', () => {
expect(roundToPlacesWithMath(0.35, 1)).toBe(0.4)
})
test('roundToPlacesWithMath 0.355 to 1 decimal place, higher', () => {
expect(roundToPlacesWithMath(0.355, 1)).toBe(0.4)
})
test('roundToPlacesWithMath to 1 decimal place, lower', () => {
expect(roundToPlacesWithMath(0.34, 1)).toBe(0.3)
})
/**
* {@link https://stackoverflow.com/questions/20701029/rounding-issue-in-math-round-tofixed}
*/
test('roundToPlacesWithMath to 2 decimal place, higher', () => {
expect(roundToPlacesWithMath(239.525, 2)).toBe(239.53)
})
/**
* {@link https://stackoverflow.com/questions/20701029/rounding-issue-in-math-round-tofixed}
*/
test('roundToPlacesWithMath 239.575 to 2 decimal place, higher', () => {
expect(roundToPlacesWithMath(239.575, 2)).toBe(239.58)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment