To print the dollar sign (‘$’) using string interpolation in Scala, you can escape the dollar sign with another dollar sign. Here’s the modified code that should give you the desired output:
scaladef main(args:Array[String]){ println("Enter the string") val inputString:String=readLine() val inputAsDouble:Double=inputString.toDouble printf(f" You owe $$$inputAsDouble%.2f") }
In this code, $$$
is used to print a single dollar sign (‘$’). Also, %2f
is used to format the double value with two decimal places. This should give you the output “You owe $2.73” when the input is “2.7255”.
المزيد من المعلومات
لفهم كيفية طباعة علامة الدولار (‘$’) باستخدام تضمين السلاسل (String Interpolation) في سكالا، يُمكننا الاعتماد على استخدام علامة الدولار مرتين ($$). يُمكن استخدام ذلك في تضمين السلسلة باستخدام الرمز ‘f’. إليك كيفية تحقيق ذلك:
scaladef main(args:Array[String]){ println("Enter the string") val inputString:String=readLine() val inputAsDouble:Double=inputString.toDouble printf(f" You owe $$${inputAsDouble}%.2f") }
في هذا الكود، $$$
يُستخدم لطباعة علامة الدولار الواحدة (‘$’). بالإضافة إلى ذلك، يتم استخدام %2f
لتنسيق القيمة العشرية مع حاشية عشرية مكونة من رقمين. هذا يجب أن يعطيك الناتج المطلوب “You owe $2.73” عندما يكون المدخل “2.7255”.