Localization settings (e.g. fr_CA) convert Number type floats to ints.

Issue #374 resolved
Former user created an issue

Requirements:

A class that contains a Number type:

public static class AmbiguousNumberType  {
    public Number number;
}

Set instance1.number to a value with a decimal component, eg, 0.001.

Convert instance1 to yaml string via 'dump'. Obtain instance2 from yaml string via 'load'.

instance1.number != instance2.number 0.001 != 0

public class FrenchLanguageNumberTest {

@Test
public void testDecimalComponentIsNotTruncated() {
    Locale originalLocale = Locale.getDefault();

    Locale.setDefault(Locale.CANADA_FRENCH);

    AmbiguousNumberType original = new AmbiguousNumberType();
    original.number = 0.001;

    Yaml yaml = new Yaml();
    String str = yaml.dump(original);

    AmbiguousNumberType interpreted = (AmbiguousNumberType)yaml.load(str);

    Locale.setDefault(originalLocale);  
    assertEquals(original.number, interpreted.number);

}

public static class AmbiguousNumberType  {
    public Number number;
}

}

Comments (9)

  1. darren_janeczek

    Note that everything would work fine if the base object was a Number -- somehow being embedded in the class triggers the problem. Forcing the NumberFormat parser to US localization seems to do the trick -- and is consistent with YAML number representation.

  2. darren_janeczek

    There may be a concern for some users who want to be vague about expressing the type as Number, but want an Integer or a Long when the value was set as an integer. Is there a potential loss of precision for Long if always interpreted as Double. I will write a couple of tests and see how they work.

  3. darren_janeczek

    Works for me:

    @Test
    public void testNumberAsLongForPrecision() {
        AmbiguousNumberType original = new AmbiguousNumberType();
        original.number = Long.MAX_VALUE;
        assertEquals(Long.class, original.number.getClass());
    
    
        Yaml yaml = new Yaml();
        String str = yaml.dump(original);
    
        AmbiguousNumberType interpreted = (AmbiguousNumberType) yaml.load(str);
    
        assertEquals(original.number.longValue(), interpreted.number.longValue());
    }
    

    Thanks.

  4. Log in to comment