Here you can find the source of decimalAlign(int width, int precision, String s)
Parameter | Description |
---|---|
width | the total number of characters desired in the formatted String |
precision | the number of digits to the right of the decimal point in the formatted String |
s | the String to be formatted |
public static String decimalAlign(int width, int precision, String s)
//package com.java2s; //License from project: LGPL public class Main { /**//from w ww . j a va 2 s . c om * Formats a String representation of a decimal number to a stated precision and total width. First the * substring following the last (right-most) decimal point is right filled with zeroes to the desired * precision. The remainder (most-significant) portion or the original String is then combined with * the formatted fraction part and the result is left-filled with space characters to the desired total width. * When the original String's only decimal point is the first character in the String, the whole number part * will be created as a single '0' character preceeded by whatever space fill is required to achieve the * desired total with. * @param width the total number of characters desired in the formatted String * @param precision the number of digits to the right of the decimal point in the formatted String * @param s the String to be formatted * @return the formatted String */ public static String decimalAlign(int width, int precision, String s) { String fraction = ""; String whole = "0."; int dot = s.lastIndexOf('.'); if (dot >= 0) { whole = s.substring(0, dot + 1); fraction = s.substring(dot + 1); } if (fraction.length() > precision) { fraction = fraction.substring(0, precision); } return fillStart(' ', width, (whole + fillEnd('0', precision, fraction))); } /** * Adds leading characters to a String as required to achieve a specified width. * @param c the pad character to use * @param width the desired width * @param value unformatted String * @return a String of the specified length (width) */ public static String fillStart(char c, int width, String value) { StringBuffer sb = new StringBuffer().append(value); while (sb.length() < width) { sb.insert(0, c); } return sb.toString(); } /** * Adds trailing characters to a String as required to achieve a specified width. * @param c the pad character to use * @param width the desired width * @param value unformatted String * @return a String of the specified length (width) */ public static String fillEnd(char c, int width, String value) { StringBuffer sb = new StringBuffer().append(value); while (sb.length() < width) { sb.append(c); } return sb.toString(); } }