Home > other >  How do we round only if the number is with .0 in decimal
How do we round only if the number is with .0 in decimal

Time:10-27

Ex 10.0 = 10 10.3 = 10.3 10.7 = 10. 7 Looking for a convenient way from Kotlin Standard library

CodePudding user response:

You can try this:

double number = 23.471;
if (number % 1 != 0)
{
    //round off here
    System.out.print ("Decimal");
}
else
{
    System.out.print ("Integer");
}

CodePudding user response:

If you want to get a string, the easiest way is to work with a string like num.toString().replace(".0",""). For numbers conversion does not make sense since the resulting type is different for different inputs.

CodePudding user response:

You can use the following function:

fun removeTrailingZeros(num: String): String {
    if(!num.contains('.')) // Return the original number if it doesn't contain decimal
        return num
    return num
        .dropLastWhile { it == '0' } // Remove trailing zero
        .dropLastWhile { it == '.' } // Remove decimal in case it's the last character in the resultant string
}

You can verify the code here

  • Related