Java Decimal Format toString(double[][] a, int decimals)

Here you can find the source of toString(double[][] a, int decimals)

Description

to String

License

LGPL

Declaration

public static String toString(double[][] a, int decimals) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
    public static String toString(double[][] a) {
        int maxLength = 12;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                String val = String.valueOf(a[i][j]);
                maxLength = Math.max(maxLength, val.length());
                while (val.length() < maxLength)
                    val = " " + val;
                sb.append(val);
            }// w  w w  .j a  v a2  s  . c  o  m
            sb.append("\n");
        }
        return sb.toString();
    }

    public static String toString(double[][] a, int decimals) {
        if (decimals < 0)
            throw new IllegalArgumentException("Number of decimals must be positive");
        StringBuilder decs = new StringBuilder("0.");
        for (int i = 0; i < decimals; i++)
            decs.append("0");
        NumberFormat decimalsFormat = new DecimalFormat(decs.toString());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                sb.append(decimalsFormat.format(a[i][j])).append(" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}

Related

  1. toString(double value)
  2. toString(double value)
  3. toString(double value, int precision)
  4. toString(double[] array)
  5. toString(Double[] input)
  6. toString(final Double value)
  7. toString(final double value, final int maxDecimalPlaces)
  8. toStringForHumans(double doubleToConvert)
  9. toStringNoDigits(double[] v)