https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

Hassaan

10/17/2023, 9:17 AM
if i format a floating number which has number of actual decimal digits less than 6, then it adds trailing zeroes so that total number of actual decimal digits remain 6
Copy code
val double1 = 1234.5678
println(String.format("%f", double1))  //1234.567800
println(String.format("%f", 1.2))      //1.200000
println(String.format("%f", 2.445))    //2.445000
what if we don’t need trailing zeroes? how would you approach?
s

Sam

10/17/2023, 9:30 AM
You can use
DecimalFormat
instead of
String.format
to get access to more formatting options.
Copy code
val formatter = DecimalFormat("#.######")
println(formatter.format(1234.5678)) // 1234.5678
println(formatter.format(1.2)) // 1.2
println(formatter.format(2.445)) // 2.445
The patterns are different from the string format ones, so look at the docs to see what options you have.
v

Vishnu Shrikar

10/17/2023, 3:00 PM
a solution may be replace "0+$" with ""
k

Klitos Kyriacou

10/17/2023, 3:26 PM
But that's complicating it even further. Start with the basics first, and keep it as simple as possible. It seems that
Double.toString()
already does what you want, so just do
println(number)
or, if you really need it to be inside a
String.format
you can use
String.format("%s", number)
(or preferably
"%s".format(number)
). If that doesn't do what you want, describe the problem in more detail.