import kotlin.math.round
import java.math.BigDecimal
/*
============================================================
Convert a decimal-like value to Long in Kotlin.
This program demonstrates:
• Conversion using round() for rounding.
• Conversion using toLong() for truncation.
• Conversion using BigDecimal.longValueExact() for strict conversion.
• A helper function that prints all conversion styles.
Notes:
• Kotlin does not have a built-in decimal type; Double and BigDecimal
are used for decimal values.
• round() returns a Double; cast to Long afterward.
• toLong() truncates the fractional part.
• BigDecimal.longValueExact() throws if the value is fractional or out of range.
============================================================
*/
// Rounds a Double to Long
fun convertDoubleToLong(value: Double): Long =
round(value).toLong()
// Truncates a Double to Long
fun castDoubleToLong(value: Double): Long =
value.toLong()
// Converts BigDecimal using truncation
fun convertBigDecimalToLong(value: BigDecimal): Long =
value.toLong()
// Converts BigDecimal strictly (throws if fractional or out of range)
fun convertBigDecimalExact(value: BigDecimal): String =
try {
value.longValueExact().toString()
} catch (e: ArithmeticException) {
"ERROR — fractional or out of range"
}
// Prints conversion styles for Double
fun showDoubleConversions(value: Double) {
println("Input decimal (Double): $value")
println("Rounded (round): ${convertDoubleToLong(value)}")
println("Truncated (toLong): ${castDoubleToLong(value)}")
println()
}
// Prints conversion styles for BigDecimal
fun showBigDecimalConversions(value: BigDecimal) {
println("Input decimal (BigDecimal): $value")
println("Truncated (toLong): ${convertBigDecimalToLong(value)}")
println("Exact (longValueExact): ${convertBigDecimalExact(value)}")
println()
}
fun main() {
// Double examples
showDoubleConversions(12.7)
showDoubleConversions(12.3)
showDoubleConversions(-5.8)
showDoubleConversions(42.0)
// BigDecimal examples
showBigDecimalConversions(BigDecimal("12.7"))
showBigDecimalConversions(BigDecimal("42"))
showBigDecimalConversions(BigDecimal("-5.8"))
}
/*
run:
Input decimal (Double): 12.7
Rounded (round): 13
Truncated (toLong): 12
Input decimal (Double): 12.3
Rounded (round): 12
Truncated (toLong): 12
Input decimal (Double): -5.8
Rounded (round): -6
Truncated (toLong): -5
Input decimal (Double): 42.0
Rounded (round): 42
Truncated (toLong): 42
Input decimal (BigDecimal): 12.7
Truncated (toLong): 12
Exact (longValueExact): ERROR ? fractional or out of range
Input decimal (BigDecimal): 42
Truncated (toLong): 42
Exact (longValueExact): 42
Input decimal (BigDecimal): -5.8
Truncated (toLong): -5
Exact (longValueExact): ERROR ? fractional or out of range
*/