Logo

Programming-Idioms

History of Idiom 65 > diff from v14 to v15

Edit summary for version 15 by :

Version 14

2015-09-05, 07:12:54

Version 15

2015-10-29, 14:05:15

Idiom #65 Format decimal number

From real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"

Idiom #65 Format decimal number

From real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"

Code
let s = format!("{:.1}%", 100.0 * x);
Code
let s = format!("{:.1}%", 100.0 * x);
Demo URL
https://play.rust-lang.org/?code=fn%20main()%20%7B%0A%20%20%20%20let%20x%20%3D%200.15625f64%3B%0A%20%20%20%20let%20s%20%3D%20format!(%22%7B%3A.1%7D%25%22%2C%20100.0%20*%20x)%3B%0A%20%20%20%20%0A%20%20%20%20println!(%22%7B%7D%22%2C%20s)%3B%0A%7D%0A&version=stable
Demo URL
https://play.rust-lang.org/?code=fn%20main()%20%7B%0A%20%20%20%20let%20x%20%3D%200.15625f64%3B%0A%20%20%20%20let%20s%20%3D%20format!(%22%7B%3A.1%7D%25%22%2C%20100.0%20*%20x)%3B%0A%20%20%20%20%0A%20%20%20%20println!(%22%7B%7D%22%2C%20s)%3B%0A%7D%0A&version=stable
Imports
import java.text.DecimalFormat;
Imports
import java.text.DecimalFormat;
Code
String s = new DecimalFormat("0.0%").format(x);
Code
String s = new DecimalFormat("0.0%").format(x);
Comments bubble
This notation handles the multiplication by 100 for you.
Comments bubble
This notation handles the multiplication by 100 for you.
Doc URL
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Doc URL
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Demo URL
https://ideone.com/acD3dm
Demo URL
https://ideone.com/acD3dm
Imports
import "fmt"
Imports
import "fmt"
Code
s := fmt.Sprintf("%.1f%%", 100.0*x)
Code
s := fmt.Sprintf("%.1f%%", 100.0*x)
Comments bubble
The litteral % must be doubled.
Comments bubble
The litteral % must be doubled.
Demo URL
https://play.golang.org/p/QVtaV89w2E
Demo URL
https://play.golang.org/p/QVtaV89w2E