1

I started learning processing since a short time ago and I came across a problem; When deviding 199.999 by 200 I want to outcome to be with 2 decimals (so the outcome should be 1 rounded of). Without formatting the outcome is 0.999995.

Code for formatting to String with 2 decimal:

float money = 199.999;
int munten = 200;

String calc1 = nf(money/munten,0,2);
println(calc1);

float calc2 = float(calc1);
println(calc2);

Prints:

1,0
NaN

I think float() wont work cause there is a comma in the String instead of a dot, I'm not sure tough. But how can I round a number to 2 decimal and still let it be a float?

Thanks for taking your time to read this,

Thomas Beumer
  • 89
  • 1
  • 14

1 Answers1

1

When I run your example on Processing 3.3.6 / macOS 10.12 (US), I get "1.00" and "1.0". This could be due to your number formatting settings creating output strings that are then not read correctly by nf().

float money;
int munten;
String s;
float f;

money = 199.999;
munten = 200;

s = nf(money/munten, 0, 2);
println(s);   // "1.00" -- or "1,0" etc. in different os language locales
f = float(s);
println(f);   // "1.0" -- or NaN error if above is not 1.0 format

f = money/munten;
println(f);   // 0.999995
s = nf(f, 0, 2);
println(s);   // 1.00 -- or local format

You can see what should be happening more clearly in the second bit of code -- don't try to convert into a String and then back out again; don't store numbers in Strings. Instead, keep everything in numeric variables up until the moment you need to display.

Also keep in mind that nf() isn't really for rounding precision, although it is often used that way:

nf() is used to add zeros to the left and/or right of a number. This is typically for aligning a list of numbers. To remove digits from a floating-point number, use the int(), ceil(), floor(), or round() functions. https://processing.org/reference/nf_.html

If you need to work around your locale, you can use Java String formatting in Processing to do so:

float fval = 199.999/200;
println(fval);   // 0.999995
String s = String.format(java.util.Locale.US,"%.2f", fval);
println(s);   // 1.00

See https://stackoverflow.com/a/5383201/7207622 for more discussion of the Java approach.

JeremyDouglass
  • 1,361
  • 2
  • 18
  • 31
  • I'm using Processing 3.3.6, never changed any settings. But on your second print "f = float(s); println(f); //1.0" I still get NaN. Your second peace of code works tough – Thomas Beumer Sep 30 '17 at 11:01
  • Right. "1,0" is NaN (not a number) because nf() reads like eg US English. The comma is probably an **operating system setting** based on your region and language, not a Processing setting. That's why I asked what your OS and language settings are. – JeremyDouglass Sep 30 '17 at 15:03