Number formatting in Scala?

Viewed 34371

I have a dynamically changing input reading from a file. The numbers are either Int or Double. Why does Scala print .0 after every Double number? Is there a way for Scala to print it the same way it reads it?

Example:

var x:Double = 1
println (x)             // This prints '1.0', I want it to print '1'
x = 1.0                 // This prints '1.0', which is good

I can't use Int because some of the input I get are Doubles. I can't use String or AnyVal because I perform some math operations.

Thank you,

7 Answers

If you are working with a Double and want to format it as a String without .0 when it's a whole number and with its decimals otherwise, then you could use String::stripSuffix:

x.toString.stripSuffix(".0")
// val x: Double = 1.34    =>   "1.34"
// val x: Double = 1.0     =>   "1"
Related