We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › More about Integers and Floats
Page Index Toggle Pages: 1
More about Integers and Floats (Read 632 times)
More about Integers and Floats
Aug 14th, 2009, 2:31pm
 
Hello, another question about floats.
I want a float with no more then one decimal and I managed to achieve this by writing:

Code:

float a = PI;
int b = 2;
print(float(int(a/(b+.0)*10))/10); //Prints 1.5


but I pretend there must be an easier way?
h
Re: More about Integers and Floats
Reply #1 - Aug 15th, 2009, 9:00am
 
This is an excruciatingly round-about way of going about this, but it works. Not sure if there is something more efficient. You could easily just stick this stuff in its own class, or even just a custom method to simplify the process in your actual code.

Code:

import java.util.Formatter; //have to import this first
Formatter formatter = new Formatter(); //initialize class

formatter.format("%.2f", 123.456789); // number and precision
String s = formatter.toString(); //convert result to string
try{
 float f = Float.valueOf(s).floatValue(); //convert to float
 println("float f = "+f); //prints 123.45
} catch(NumberFormatException nfe){
 println("NumberFormatException: "+nfe.getMessage());
}
Re: More about Integers and Floats
Reply #2 - Aug 15th, 2009, 9:29am
 
Use nf().

String formatted = nf(HALF_PI, 1);
println(formatted);
Page Index Toggle Pages: 1