Format in kotlin string templates
Kotlin has an excellent feature called string templates. I really love it.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
But is it possible to have any formatting in the templates? For example I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:
val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
string-formatting kotlin
add a comment |
Kotlin has an excellent feature called string templates. I really love it.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
But is it possible to have any formatting in the templates? For example I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:
val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
string-formatting kotlin
add a comment |
Kotlin has an excellent feature called string templates. I really love it.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
But is it possible to have any formatting in the templates? For example I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:
val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
string-formatting kotlin
Kotlin has an excellent feature called string templates. I really love it.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
But is it possible to have any formatting in the templates? For example I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:
val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
string-formatting kotlin
string-formatting kotlin
edited Jan 7 '16 at 3:47
akhyar
3,07913053
3,07913053
asked Apr 15 '14 at 14:12
MajesticRaMajesticRa
6,33694865
6,33694865
add a comment |
add a comment |
7 Answers
7
active
oldest
votes
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
|
show 4 more comments
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
add a comment |
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
add a comment |
Its simple,
Use:
val str:String = "%.2f".format(3.14159)
add a comment |
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
add a comment |
A lot of answers refer to String.format and related, but not the correct position in the latest master branch. For reference, this is where it's located now.
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
add a comment |
Try take. It returns a list containing first n elements.
val pi = 3.14159265358979323
val s = pi.take(4)
But it's just about the collections as rekire said, who politely corrected me in the comment below.
You can convert to string, use take and convert back to Double.
val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()
Not the best idea though but it works.
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23086291%2fformat-in-kotlin-string-templates%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
|
show 4 more comments
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
|
show 4 more comments
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
answered Apr 15 '14 at 15:21
Andrey BreslavAndrey Breslav
14.2k34951
14.2k34951
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
|
show 4 more comments
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
5
5
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
Is this available now?
– Ragunath Jawahar
Mar 13 '15 at 8:00
3
3
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
@RagunathJawahar, the answer is still up-to-date, we didn't improve on it yet
– Andrey Breslav
Mar 13 '15 at 12:09
1
1
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
@AndreyBreslav chance Kotlin could copy C# style of string formatting? Of all of the different formatting types I've used, it's by far the best.
– Nick
Nov 13 '17 at 22:07
2
2
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
@AndreyBreslav How about now? Is this available?
– cihan adil seven
Jun 18 '18 at 14:25
5
5
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
Am I mistaken or is this still not available almost 4 years later?
– Warkst
Jan 19 at 8:31
|
show 4 more comments
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
add a comment |
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
add a comment |
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
answered Nov 3 '15 at 6:22
akhyarakhyar
3,07913053
3,07913053
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
add a comment |
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
2
2
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
I'm guessing he meant this documentation: docs.oracle.com/javase/8/docs/api/java/lang/…
– stuckj
Dec 27 '17 at 5:35
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
@Rob See also discussion on the documentation
– Matt Mc
Mar 9 '18 at 4:44
add a comment |
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
add a comment |
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
add a comment |
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
Kotlin's String class has a format function now, which internally uses Java's String.format
method:
/**
* Uses this string as a format string and returns a string obtained by substituting the specified arguments,
* using the default locale.
*/
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
Usage
val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
edited Dec 8 '17 at 9:51
Willi Mentzel
10.3k114771
10.3k114771
answered Dec 8 '17 at 0:33
user1767754user1767754
10.1k57184
10.1k57184
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
add a comment |
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
String.Companion.format is not found now in Kotlin v1.2.21. What is the alternative?.
– Sai Kiran
Feb 3 '18 at 9:07
add a comment |
Its simple,
Use:
val str:String = "%.2f".format(3.14159)
add a comment |
Its simple,
Use:
val str:String = "%.2f".format(3.14159)
add a comment |
Its simple,
Use:
val str:String = "%.2f".format(3.14159)
Its simple,
Use:
val str:String = "%.2f".format(3.14159)
edited Nov 22 '18 at 22:38
pableiros
5,85884563
5,85884563
answered Aug 25 '18 at 11:53
masoomyfmasoomyf
13536
13536
add a comment |
add a comment |
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
add a comment |
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
add a comment |
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
edited Dec 8 '17 at 9:57
answered Dec 8 '17 at 9:14
Willi MentzelWilli Mentzel
10.3k114771
10.3k114771
add a comment |
add a comment |
A lot of answers refer to String.format and related, but not the correct position in the latest master branch. For reference, this is where it's located now.
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
add a comment |
A lot of answers refer to String.format and related, but not the correct position in the latest master branch. For reference, this is where it's located now.
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
add a comment |
A lot of answers refer to String.format and related, but not the correct position in the latest master branch. For reference, this is where it's located now.
A lot of answers refer to String.format and related, but not the correct position in the latest master branch. For reference, this is where it's located now.
answered Apr 9 '18 at 16:31
MartmistsMartmists
1274
1274
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
add a comment |
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
1
1
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
Link has expired? 404 - not found.
– Scre
Oct 21 '18 at 1:03
add a comment |
Try take. It returns a list containing first n elements.
val pi = 3.14159265358979323
val s = pi.take(4)
But it's just about the collections as rekire said, who politely corrected me in the comment below.
You can convert to string, use take and convert back to Double.
val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()
Not the best idea though but it works.
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
add a comment |
Try take. It returns a list containing first n elements.
val pi = 3.14159265358979323
val s = pi.take(4)
But it's just about the collections as rekire said, who politely corrected me in the comment below.
You can convert to string, use take and convert back to Double.
val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()
Not the best idea though but it works.
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
add a comment |
Try take. It returns a list containing first n elements.
val pi = 3.14159265358979323
val s = pi.take(4)
But it's just about the collections as rekire said, who politely corrected me in the comment below.
You can convert to string, use take and convert back to Double.
val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()
Not the best idea though but it works.
Try take. It returns a list containing first n elements.
val pi = 3.14159265358979323
val s = pi.take(4)
But it's just about the collections as rekire said, who politely corrected me in the comment below.
You can convert to string, use take and convert back to Double.
val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()
Not the best idea though but it works.
edited Nov 13 '18 at 9:34
answered Sep 5 '18 at 20:15
KzafKzaf
106110
106110
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
add a comment |
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
if the author just wanted to print "3.14", he would not ask about it
– Alexey Subbota
Dec 10 '18 at 20:33
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23086291%2fformat-in-kotlin-string-templates%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown