Search code examples
javakotlindoubleprecision

Double to Int with removing precision point dynamically


Is there a way in Kotlin, or Java to parse Double to Int knowing that all the doubles will not exceed the Int memory limit? examples:

Double Int
1,123 1123
1,1 11
1,12345 11234
0,12345 1234

I know we can parse it to string first and remove the '.' and then to Int but I want a more effective way.


Solution

  • Assuming that you want to keep all the significant digits you should use BigDecimal to do the conversion and transformation without missing information:

    import java.math.BigDecimal;
    
    public class MyClass {
        public static void main(String args[]) {
          BigDecimal x=BigDecimal.valueOf(1.12345);
          int y=x.unscaledValue().intValueExact();
          System.out.println("y = " + y);
        }
    }
    

    Output:

    y = 112345
    

    valueOf() is needed to create a BigDecimal from a floating point type without representation errors. intValueExact() will throw an exception if the result is out of range for an int.

    Note that this solution keeps the 5 at the end of the number unlike your example.