Suppose, I take an irrational number, q, and an integer n, and I want to print the truncated value of q after keeping exactly n digits after the decimal.
Example: Input: q = 3.14159625, n = 3 Output: 3.141
You can do this by using System.out.printf
assuming you want correct rounding
String format = "%." + n + "f";
System.out.printf(format, q);
int n = 3;
float q = 3.141592625f;
String format = "%." + n + "f";
System.out.printf(format, q);
output
3.142
if you really want to truncate you can convert to a String, then
int n = 3;
float q = 3.141592625f;
String str = Float.toString(q);
int index = str.indexOf('.');
System.out.println(str.substring(0, index + n + 1));
output
3.141
but you will need to check for valid index of and string length