com.hfg.units.BaseSIUnitConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of com_hfg Show documentation
Show all versions of com_hfg Show documentation
com.hfg xml, html, svg, and bioinformatics utility library
package com.hfg.units;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class BaseSIUnitConverter
{
private double mScalingFactor;
private Double mOffset;
private MathContext mMathContext = sDefaultMathContext;
private static MathContext sDefaultMathContext = new MathContext(16, RoundingMode.HALF_UP);
//###########################################################################
// CONSTRUCTORS
//###########################################################################
//---------------------------------------------------------------------------
public BaseSIUnitConverter(double inScalingFactor)
{
mScalingFactor = inScalingFactor;
}
//###########################################################################
// PUBLIC METHODS
//###########################################################################
//---------------------------------------------------------------------------
public static void setDefaultMathContext(MathContext inValue)
{
sDefaultMathContext = inValue;
}
//---------------------------------------------------------------------------
public BaseSIUnitConverter setMathContext(MathContext inValue)
{
mMathContext = inValue;
return this;
}
//---------------------------------------------------------------------------
public BaseSIUnitConverter setOffset(Double inValue)
{
mOffset = inValue;
return this;
}
//---------------------------------------------------------------------------
public Double apply(Double inValue)
{
BigDecimal bigDecimalValue = allocateBigDecimal(inValue).multiply(allocateBigDecimal(mScalingFactor));
if (mOffset != null)
{
bigDecimalValue = bigDecimalValue.add(allocateBigDecimal(mOffset));
}
return bigDecimalValue.doubleValue();
}
//---------------------------------------------------------------------------
public Double reverse(Double inValue)
{
BigDecimal bigDecimalValue = allocateBigDecimal(inValue).divide(allocateBigDecimal(mScalingFactor), mMathContext);
if (mOffset != null)
{
bigDecimalValue = bigDecimalValue.subtract(allocateBigDecimal(mOffset));
}
return bigDecimalValue.doubleValue();
}
//###########################################################################
// PRIVATE METHODS
//###########################################################################
//---------------------------------------------------------------------------
protected BigDecimal allocateBigDecimal(double inValue)
{
return new BigDecimal(Double.toString(inValue), mMathContext);
}
}