Example usage for java.text DecimalFormat DecimalFormat

List of usage examples for java.text DecimalFormat DecimalFormat

Introduction

In this page you can find the example usage for java.text DecimalFormat DecimalFormat.

Prototype

public DecimalFormat(String pattern, DecimalFormatSymbols symbols) 

Source Link

Document

Creates a DecimalFormat using the given pattern and symbols.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DecimalFormat format = new DecimalFormat("##.##", DecimalFormatSymbols.getInstance());

    System.out.println(format.format(-123456789.12345678));

}

From source file:DecimalFormatDemo.java

static public void main(String[] args) {

    customFormat("###,###.###", 123456.789);
    customFormat("###.##", 123456.789);
    customFormat("000000.000", 123.78);
    customFormat("$###,###.###", 12345.67);
    customFormat("\u00a5###,###.###", 12345.67);

    Locale currentLocale = new Locale("en", "US");

    DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
    unusualSymbols.setDecimalSeparator('|');
    unusualSymbols.setGroupingSeparator('^');
    String strange = "#,##0.###";
    DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
    weirdFormatter.setGroupingSize(4);/* w ww  .  j a  v  a2s  .  c o  m*/
    String bizarre = weirdFormatter.format(12345.678);
    System.out.println(bizarre);

    Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"), new Locale("fr", "FR") };

    for (int i = 0; i < locales.length; i++) {
        localizedFormat("###,###.###", 123456.789, locales[i]);
    }

}

From source file:fr.cs.examples.attitude.EarthObservation.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///from  w  ww .  ja  va  2  s  .co m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //  Initial state definition : date, orbit
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        // Attitudes sequence definition
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>());
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>());

        final AttitudesSequence attitudesSequence = new AttitudesSequence();
        final AttitudesSequence.SwitchHandler switchHandler = new AttitudesSequence.SwitchHandler() {
            public void switchOccurred(AttitudeProvider preceding, AttitudeProvider following,
                    SpacecraftState s) {
                if (preceding == dayObservationLaw) {
                    output.add(s.getDate() + ": switching to night law");
                } else {
                    output.add(s.getDate() + ": switching to day law");
                }
            }
        };
        attitudesSequence.addSwitchingCondition(dayObservationLaw, nightRestingLaw, dayNightEvent, false, true,
                10.0, AngularDerivativesFilter.USE_R, switchHandler);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, dayObservationLaw, nightDayEvent, true, false,
                10.0, AngularDerivativesFilter.USE_R, switchHandler);
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
        }

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);

        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(180.0, new OrekitFixedStepHandler() {
            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    DecimalFormatSymbols angleDegree = new DecimalFormatSymbols(Locale.US);
                    angleDegree.setDecimalSeparator('\u00b0');
                    DecimalFormat ad = new DecimalFormat(" 00.000;-00.000", angleDegree);
                    // the Earth position in spacecraft frame should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    output.add(currentState.getDate() + " " + ad.format(FastMath.toDegrees(eclipseAngle)) + " "
                            + ad.format(FastMath.toDegrees(pointingOffset)));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        // Propagate from the initial date for the fixed duration
        SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(12600.));

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

        System.out.println("Propagation ended at " + finalState.getDate());

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:com.squarespace.template.plugins.platform.PlatformUtils.java

public static String formatPercentage(double percentage, boolean trim, Locale locale) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
    String pattern = trim ? "#,##0.###" : "#,##0.00#";
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    return format.format(percentage);
}

From source file:dataGen.DataGen.java

/**
 * Creates normal or uniform distributed Test-Data, without correlation.
 * The resulting Data is stored in the resources Folder.
 * @param dimensions//from ww  w  . j  a v a2s  .c om
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static void genData(int dimensions, int rowCount) throws IOException {
    logger.info("Generating uniform random Data with " + rowCount + " Tuples in " + dimensions + " dimensions");
    Writer fw = new FileWriter("src/main/resources/random-" + rowCount + "-" + dimensions + ".dat");
    Random gen = new Random();

    for (int i = 1; i <= rowCount; i++) {
        // Each Row should start with the Row count
        String row = i + " ";
        // Files should be created OS/Language independent
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
        dfs.setDecimalSeparator('.');
        NumberFormat nf = new DecimalFormat("0.000000000", dfs);

        for (int j = 0; j < dimensions; j++) {
            Float n = gen.nextFloat();
            row = row + nf.format(n) + " ";
        }
        fw.write(row);
        fw.append(System.getProperty("line.separator"));
    }
    fw.close();
    logger.info(rowCount + " entries generated");
}

From source file:de.perdian.commons.lang.conversion.impl.converters.AbstractNumberFormatConverter.java

@Override
protected NumberFormat resolveDefaultFormat(Locale locale) {
    return Optional.ofNullable(this.getPattern())
            .<NumberFormat>map(pattern -> new DecimalFormat(pattern, new DecimalFormatSymbols(locale)))
            .orElseGet(NumberFormat::getInstance);
}

From source file:com.aw.core.format.NullDecimalFormat.java

/**
 * Constructor//from  www.j  a v a2  s  . c  o  m
 *
 * @param pattern
 */
public NullDecimalFormat(String pattern) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator(',');
    decimalFormat = new DecimalFormat(pattern, symbols);
}

From source file:ai.grakn.graql.internal.util.StringConverter.java

/**
 * @param value a value in the graph/*from  w  w  w.ja v a  2 s .  co m*/
 * @return the string representation of the value (using quotes if it is already a string)
 */
public static String valueToString(Object value) {
    if (value instanceof String) {
        return quoteString((String) value);
    } else if (value instanceof Double) {
        DecimalFormat df = new DecimalFormat("#", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(12);
        df.setMinimumIntegerDigits(1);
        return df.format(value);
    } else {
        return value.toString();
    }
}

From source file:com.haulmont.chile.core.datatypes.impl.DoubleDatatype.java

@Override
public String format(Object value, Locale locale) {
    if (value == null) {
        return "";
    }// www  .jav a  2 s.co m

    FormatStrings formatStrings = AppBeans.get(FormatStringsRegistry.class).getFormatStrings(locale);
    if (formatStrings == null) {
        return format(value);
    }

    DecimalFormatSymbols formatSymbols = formatStrings.getFormatSymbols();
    NumberFormat format = new DecimalFormat(formatStrings.getDoubleFormat(), formatSymbols);
    return format.format(value);
}

From source file:com.haulmont.chile.core.datatypes.impl.IntegerDatatype.java

@Override
public String format(Object value, Locale locale) {
    if (value == null)
        return "";

    FormatStrings formatStrings = AppBeans.get(FormatStringsRegistry.class).getFormatStrings(locale);
    if (formatStrings == null)
        return format(value);

    DecimalFormatSymbols formatSymbols = formatStrings.getFormatSymbols();
    NumberFormat format = new DecimalFormat(formatStrings.getIntegerFormat(), formatSymbols);
    return format.format(value);
}