Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format a string when interpolated in Julia?

Tags:

In Python 3, I would

print_me = "Look at this significant figure formatted number: {:.2f}!".format(floating_point_number) print(print_me) 

or

print_me = f"Look at this significant figure formatted number: {floating_point_number:.2f}!" print(print_me) 

In Julia

print_me = "Look at this significant figure formatted number: $floating_point_number" print(print_me) 

but this would yield say

Look at this significant figure formatted number: 61.61616161616161 

How do I get Julia to restrict the number of decimal places it displays? Note that the necessary storage of the string to be printed, to my knowledge, rules out using the @printf macro.

This works, but does not seem stylistically correct.

floating_point_number = round(floating_point_number,2) print_me = "Look at this significant figure formatted number: $floating_point_number" print(print_me) 
like image 458
Joshua Cook Avatar asked May 04 '16 14:05

Joshua Cook


People also ask

Which is the correct syntax of string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.

Which character should be used for string interpolation?

To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.

Does Julia have F strings?

jl package in Julia, which provides Python f-string functionality.

How do I print strings in Julia?

Julia uses printf() function similar to C, in order to format strings. Here, we print using the macro @printf. Characters: In the following code, we are storing a single letter 'c' in the variable named 'character'. The character variable is then printed using '%c' format specifier as its data type is char.


1 Answers

You can use @sprintf macro from the standard library package Printf. This returns a string rather than just printing it as @printf.

using Printf x = 1.77715 print("I'm long: $x, but I'm alright: $(@sprintf("%.2f", x))") 

Output:

I'm long: 1.77715, but I'm alright: 1.78 
like image 187
niczky12 Avatar answered Sep 24 '22 02:09

niczky12