user1162715
user1162715

Reputation:

How to type π (pi) in Java?

Is there a character within the Math API that allows for representing the character π?

Upvotes: 10

Views: 24876

Answers (4)

Anonymous
Anonymous

Reputation: 1

If you want to use the value of PI, you can use Math.PI after importing Math class using import java.lang.Math;

Upvotes: -2

asela38
asela38

Reputation: 4644

If you want to write this to a file you can achieve it through Unicodes, below is an example of how,

import java.io.*;
public class Test {

    public static void main(String[] args) throws Exception{
        BufferedWriter out = 
                    new BufferedWriter(new OutputStreamWriter(
                          new FileOutputStream("out.txt"),"UTF8"));     

    out.write("alpha = \u03B1, beta = \u03B2 ,pi = \u03C0");
    out.flush();
    out.close();
}
}

out put : alpha = α, beta = β ,pi = π

Upvotes: 3

ruakh
ruakh

Reputation: 183351

You don't even need to use the Math API. In Java source code, this:

\u03C0

is equivalent to this:

π

and you can even use it in an identifier; these two are equivalent:

final String \u03C0 = "\u03C0";
final String π = "π";

(As the spec puts it:

A Unicode escape of the form \uxxxx, where xxxx is a hexadecimal value, represents the UTF-16 code unit whose encoding is xxxx. This translation step allows any program to be expressed using only ASCII characters.

See http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.2.)

Upvotes: 24

Related Questions