Skip to content

Commit

Permalink
Merge pull request #95 from cyrille-leclerc/issues/91-influxdb-float-…
Browse files Browse the repository at this point in the history
…formatting

[#91] InfluxDB - Decimal number formatting (float, double and BigDecimal)
  • Loading branch information
Cyrille Le Clerc authored Feb 16, 2017
2 parents 001ddc9 + 7a919cc commit 019df0e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/main/java/org/jmxtrans/agent/influxdb/InfluxMetric.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,35 @@
*/
package org.jmxtrans.agent.influxdb;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import org.jmxtrans.agent.util.StringUtils2;

import javax.annotation.concurrent.NotThreadSafe;

/**
* @author Kristoffer Erlandsson
*/
public class InfluxMetric {

private static final String FIELD_NAME = "value";

/*
* See https://github.com/influxdata/influxdb-java/blob/influxdb-java-2.5/src/main/java/org/influxdb/dto/Point.java#L321
*/
protected final static NumberFormat NUMBER_FORMAT;
static {
NUMBER_FORMAT = NumberFormat.getInstance(Locale.ENGLISH);
NUMBER_FORMAT.setMaximumFractionDigits(340);
NUMBER_FORMAT.setGroupingUsed(false);
NUMBER_FORMAT.setMinimumFractionDigits(1);
}
private final long timestampMillis;
private final List<InfluxTag> tags;
private final String measurement;
Expand Down Expand Up @@ -83,6 +100,11 @@ private String valueAsStr() {
if (value instanceof Integer || value instanceof Long) {
return value.toString() + "i";
}
if (value instanceof Float || value instanceof Double || value instanceof BigDecimal) {
synchronized (NUMBER_FORMAT) {
return NUMBER_FORMAT.format(value);
}
}
return value.toString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ public void toInfluxFormatInteger() throws Exception {
assertThat(metric.toInfluxFormat(), equalTo("foo value=1i 2123"));
}

/**
* A very big float will get formatted with an exponent
* See https://github.com/jmxtrans/jmxtrans-agent/issues/91
*/
@Test
public void toInfluxFormatBigFloat() throws Exception {
InfluxMetric metric = new InfluxMetric("foo", EMPTY_TAG_LIST, 123_456_789.012_345, 2123l);
assertThat(metric.toInfluxFormat(), equalTo("foo value=123456789.012345 2123"));
}

@Test
public void toInfluxFormatLong() throws Exception {
InfluxMetric metric = new InfluxMetric("foo", EMPTY_TAG_LIST, 1l, 2123l);
Expand Down

0 comments on commit 019df0e

Please sign in to comment.