if i format a floating number which has number of ...
# getting-started
h
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
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
a solution may be replace "0+$" with ""
k
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.