java - Truncating float to the two first non-zero decimal digits -
i want truncate floating point numbers in java 2 first non-zero decimal digits. example, 0.000134
0.00013
, or 11.00401
11.0040
.
the solution can think of strip integral part, , multiply 10 until number bigger or equal 10. truncate original float number of multiplications
decimal digits.
but might have operation often, i'm looking faster solution.
my test code:
public static string truncateto2nonzero(double f) { int integral = (int)f; double decimal = f - integral; int digits = 0; while (decimal < 10) { decimal *= 10; digits++; } double ret = (int)decimal / math.pow(10, digits); ret += integral; return double.tostring(ret); } public static void main(string args[]) { final int tests = 1000000; double[] floats = new double[tests]; random random = new random(); (int = 0; < tests; ++i) { int zeros = random.nextint(6) + 3; // divide 10^zeros double digits = random.nextint(100) + 100; // 3 last digits floats[i] = digits / math.pow(10,zeros) + random.nextint(20) + 1; } long starttime = system.nanotime(); (int = 0; < tests; ++i) truncateto2nonzero(floats[i]); long endtime = system.nanotime(); long duration = endtime - starttime; system.out.println(duration / 1000000); // in milliseconds }
i'm using windows 7 home premium 64-bit. output of java -version
:
java version "1.8.0_20" java(tm) se runtime environment (build 1.8.0_20-b26) java hotspot(tm) 64-bit server vm (build 25.20-b23, mixed mode)
when want "truncate" sounds display format. being said floats not friendly this. bigdecimals are. should give start, needs error checking of course.
static string roundtolasttwodecimaldigits(float f) { // split whole number , decimals string[] floatparts = new bigdecimal(f).toplainstring().split("\\."); int wholenumberportion = integer.parseint(floatparts[0]); // count zeroes string decimalportion = floatparts[1]; int numdecimalplaces = 0; while (decimalportion.charat(numdecimalplaces) == '0') numdecimalplaces++; // 3 digits round string toround = decimalportion.substring(numdecimalplaces, numdecimalplaces + 3); int decimalforrounding = math.round(float.parsefloat(toround) / 10); stringbuilder sb = new stringbuilder(); sb.append(wholenumberportion); sb.append("."); (int = 0; < numdecimalplaces; i++) sb.append("0"); sb.append(decimalforrounding); return sb.tostring(); }
Comments
Post a Comment