1/*  Copyright (c) 2000-2006 hamcrest.org
2 */
3package org.hamcrest.number;
4
5import org.hamcrest.Description;
6import org.hamcrest.Matcher;
7import org.hamcrest.Factory;
8import org.hamcrest.TypeSafeMatcher;
9
10
11/**
12 * Is the value a number equal to a value within some range of
13 * acceptable error?
14 */
15public class IsCloseTo extends TypeSafeMatcher<Double> {
16    private final double error;
17    private final double value;
18
19    public IsCloseTo(double value, double error) {
20        this.error = error;
21        this.value = value;
22    }
23
24    public boolean matchesSafely(Double item) {
25        return Math.abs((item - value)) <= error;
26    }
27
28    public void describeTo(Description description) {
29        description.appendText("a numeric value within ")
30                .appendValue(error)
31                .appendText(" of ")
32                .appendValue(value);
33    }
34
35    @Factory
36    public static Matcher<Double> closeTo(double operand, double error) {
37        return new IsCloseTo(operand, error);
38    }
39
40}
41