br.com.objectos.io.flat.DoubleField Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2015 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.io.flat;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Set;
import br.com.objectos.io.flat.annotation.DecimalOption;
import com.google.common.collect.ImmutableSet;
/**
* @author [email protected] (Marcio Endo)
*/
class DoubleField extends Field {
final double value;
private final int precision;
private final int scale;
private final Set optionSet;
private DoubleField(double value, int precision, int scale, Set optionSet) {
this.value = value;
this.precision = precision;
this.scale = scale;
this.optionSet = optionSet;
}
public static DoubleField get(double value, int precision, int scale, DecimalOption... options) {
Set optionSet = ImmutableSet.copyOf(options);
return new DoubleField(value, precision, scale, optionSet);
}
public static DoubleField get(
double value, int precision, int scale, DoubleValueCondition condition, String text, DecimalOption... options) {
Set optionSet = ImmutableSet.copyOf(options);
return new Conditional(value, precision, scale, optionSet, condition, text);
}
@Override
void tryToWriteTo(FlatAppendable out) throws IOException {
BigDecimal multiplier = new BigDecimal((int) Math.pow(10, scale));
int normalized = new BigDecimal(value).setScale(scale, RoundingMode.HALF_EVEN).multiply(multiplier).intValue();
StringBuilder format = new StringBuilder();
format.append('%');
for (DecimalOption option : optionSet) {
option.formatString(format);
}
format.append(precision);
format.append('d');
out.append(String.format(format.toString(), normalized));
}
private static class Conditional extends DoubleField {
private final DoubleValueCondition condition;
private final String text;
public Conditional(double value,
int precision,
int scale,
Set optionSet,
DoubleValueCondition condition,
String text) {
super(value, precision, scale, optionSet);
this.condition = condition;
this.text = text;
}
@Override
void tryToWriteTo(FlatAppendable out) throws IOException {
if (condition.matches(value)) {
out.append(text);
} else {
super.tryToWriteTo(out);
}
}
}
}