From 7a919cc33242212151b7d90a753f89805dc05c54 Mon Sep 17 00:00:00 2001 From: Cyrille Le Clerc Date: Thu, 16 Feb 2017 11:00:01 +0100 Subject: [PATCH] Fix #91, fine tune decimal number formatting. The expected string for `123_456_789.012_345 ` is `123456789.012345` and is NOT `1.23456789012345E8` as we generate today. See https://github.com/influxdata/influxdb-java/blob/influxdb-java-2.5/src/main/java/org/influxdb/dto/Point.java#L321 --- .../jmxtrans/agent/influxdb/InfluxMetric.java | 22 +++++++++++++++++++ .../influxdb/InfluxMetricConverterTest.java | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jmxtrans/agent/influxdb/InfluxMetric.java b/src/main/java/org/jmxtrans/agent/influxdb/InfluxMetric.java index 0316cfcf..04bbd0f8 100644 --- a/src/main/java/org/jmxtrans/agent/influxdb/InfluxMetric.java +++ b/src/main/java/org/jmxtrans/agent/influxdb/InfluxMetric.java @@ -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 tags; private final String measurement; @@ -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(); } diff --git a/src/test/java/org/jmxtrans/agent/influxdb/InfluxMetricConverterTest.java b/src/test/java/org/jmxtrans/agent/influxdb/InfluxMetricConverterTest.java index c8aa4e75..61dcac3c 100644 --- a/src/test/java/org/jmxtrans/agent/influxdb/InfluxMetricConverterTest.java +++ b/src/test/java/org/jmxtrans/agent/influxdb/InfluxMetricConverterTest.java @@ -90,7 +90,7 @@ public void toInfluxFormatInteger() throws Exception { @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=1.23456789012345E8 2123")); + assertThat(metric.toInfluxFormat(), equalTo("foo value=123456789.012345 2123")); } @Test