Here you can find the source of round(String num, int length)
private static String round(String num, int length)
//package com.java2s; //License from project: Apache License public class Main { private static String round(String num, int length) { // Helper function for realToString. // Round off num to the given field width if (num.indexOf('.') < 0) return num; if (num.length() <= length) return num; if (num.charAt(length) >= '5' && num.charAt(length) != '.') { char[] temp = new char[length + 1]; int ct = length; boolean rounding = true; for (int i = length - 1; i >= 0; i--) { temp[ct] = num.charAt(i); if (rounding && temp[ct] != '.') { if (temp[ct] < '9') { temp[ct]++;// w w w . ja va 2 s . c o m rounding = false; } else temp[ct] = '0'; } ct--; } if (rounding) { temp[ct] = '1'; ct--; } // ct is -1 or 0 return new String(temp, ct + 1, length - ct); } else return num.substring(0, length); } }