Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which locale is used for kotlin's string templates?

Tags:

format

kotlin

The documentation does not cover which locale is used to convert variables to strings. An example:

val d = 0.1234
val s = "$d"

Will s be 0.1234 or 0,1234 which reflects my machine's local (de_AT)?

Any means to adjust it?

like image 566
linqu Avatar asked Jan 04 '23 08:01

linqu


1 Answers

TL;DR: you can not adjust it.

If you look at the bytecode when you use string interpolation, you'll see that it uses StringBuilder under the hood (which is the same as what modern Java compilers do with + concatenation).

Just as an example, if you take this code:

val kt = "Kotlin"
println("hello $kt")

The string template operation looks like this in the bytecode (which is moderately legible):

LINENUMBER 8 L2
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
LDC "hello "
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 1
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
ASTORE 2

Back to the point. So now the question is what StringBuilder uses when you append a double to it. If you look up the documentation, it uses the String.valueOf(double) method, which in turn uses Double.toString(double), for which you can find the documentation here to see how it formats the values given to it. Short summary: it uses . as the decimal separator, and gives you exponential notation with E for very small and very large numbers.

The documentation in the last link suggests to use NumberFormat if you want to format it differently. I'd also suggest String.format, which you can pass a Locale to.

like image 86
zsmb13 Avatar answered Jan 08 '23 05:01

zsmb13