package net.openhft.chronicle.bytes;

import net.openhft.chronicle.core.Maths;
import org.junit.Test;

import java.text.DecimalFormat;
import java.util.Random;

import static net.openhft.chronicle.bytes.UnsafeTextBytesTest.testAppendDouble;
import static org.junit.Assert.assertEquals;

public class Issue128Test {
    private static final DecimalFormat DF;

    static {
        DecimalFormat df = new DecimalFormat();
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(30);
        DF = df;
    }

    static String toDecimal(double d) {
        return DF.format(d);
    }

    @Test
//    @Ignore("https://github.com/OpenHFT/Chronicle-Bytes/issues/128")
    public void testCorrect() {
        Bytes bytes = Bytes.allocateDirect(32);
        Random rand = new Random();
        try {
            for (int i = 0; i < 10000; i++) {
                // TODO FIX https://github.com/OpenHFT/Chronicle-Bytes/issues/128
                double smallest = 0.001;
                double v = Math.pow(smallest, rand.nextDouble());
                // TODO FIX https://github.com/OpenHFT/Chronicle-Bytes/issues/128
                v = Maths.round8(v);
                doTest(bytes, v);
                doTest(bytes, 1 + v);
            }
        } finally {
            bytes.releaseLast();
        }
    }

    public void doTest(Bytes bytes, double v) {
        String format = DF.format(v);
        String output = testAppendDouble(bytes, v);
        if (Double.parseDouble(output) != v || format.length() != output.length())
            assertEquals(DF.format(v), output);
    }

}

@@ -35,49 +35,8 @@
 s;%0A%0A
-import net.openhft.chronicle.core.Maths;%0A
 impo
@@ -90,33 +90,8 @@
 mat;
-%0Aimport java.util.Random;
 %0A%0Aim
@@ -701,49 +701,50 @@
     
-Random rand = new Random();%0A        try %7B
+try %7B%0A            // odd ones are trouble.
 %0A   
@@ -769,25 +769,32 @@
 i = 
-0
+1
 ; i %3C 1
-0
+_000_
 000; i
-++
+ += 2
 ) %7B%0A
@@ -813,113 +813,118 @@
     
-// TODO FIX https://github.com/OpenHFT/Chronicle-Bytes/issues/128%0A                double smallest = 0.001
+double v6 = (double) i / 1_000_000;%0A                doTest(bytes, v6);%0A                doTest(bytes, 999 + v6)
 ;%0A  
@@ -949,167 +949,124 @@
 le v
+7
  = 
-Math.pow(smallest, rand.nextDouble());%0A                // TODO FIX https://github.com/OpenHFT/Chronicle-Bytes/issues/128%0A                v = Maths.round8(v)
+(double) i / 10_000_000;%0A                doTest(bytes, v7);%0A                double v8 = (double) i / 100_000_000
 ;%0A  
@@ -1086,35 +1086,90 @@
  doTest(bytes, v
+8
 );%0A
+                double v9 = (double) i / 100_000_000;%0A
                 
@@ -1186,13 +1186,10 @@
 es, 
-1 + 
 v
+9
 );%0A 
@@ -1540,17 +1540,80 @@
 utput);%0A
+//            System.out.println(DF.format(v)+%22 != %22 + output);%0A
     %7D%0A
-%0A
 %7D%0A

Fix trailing zeros in decimals, closes https://github.com/OpenHFT/Chronicle-Bytes/issues/128