Search in sources :

Example 31 with DecimalFormatSymbols

use of java.text.DecimalFormatSymbols in project jphp by jphp-compiler.

the class NumUtils method format.

@FastMethod
@Signature({ @Arg("number"), @Arg("pattern"), @Arg(value = "decSep", optional = @Optional(".")), @Arg(value = "groupSep", optional = @Optional(",")) })
public static Memory format(Environment env, Memory... args) {
    try {
        char decSep = args[2].toChar();
        char groupSep = args[3].toChar();
        DecimalFormat decimalFormat;
        if (decSep == '.' && groupSep == ',')
            decimalFormat = new DecimalFormat(args[1].toString(), DEFAULT_DECIMAL_FORMAT_SYMBOLS);
        else {
            DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
            formatSymbols.setZeroDigit('0');
            formatSymbols.setDecimalSeparator(decSep);
            formatSymbols.setGroupingSeparator(groupSep);
            decimalFormat = new DecimalFormat(args[1].toString(), formatSymbols);
        }
        return new StringMemory(decimalFormat.format(args[0].toDouble()));
    } catch (IllegalArgumentException e) {
        return Memory.FALSE;
    }
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) StringMemory(php.runtime.memory.StringMemory) FastMethod(php.runtime.annotation.Runtime.FastMethod)

Example 32 with DecimalFormatSymbols

use of java.text.DecimalFormatSymbols in project pcgen by PCGen.

the class ExportHandler method mathMode.

/**
	 * Math Mode - Most of the code logic was copied from PlayerCharacter.getVariableValue
	 * included a treatment for math with attack routines (for example +6/+1 - 2 = +4/-1)
	 *
	 * @param aString The string to be converted
	 * @param aPC the PC being exported
	 * @return String
	 */
private String mathMode(String aString, PlayerCharacter aPC) {
    String str = aString;
    // Deal with Knowledge () type tokens
    str = processBracketedTokens(str, aPC);
    // Replace all square brackets with curved ones
    str = str.replaceAll(Pattern.quote("["), "(");
    str = str.replaceAll(Pattern.quote("]"), ")");
    // A list of mathematical delimiters
    final String delimiter = "+-/*";
    String valString = "";
    final int ADDITION_MODE = 0;
    final int SUBTRACTION_MODE = 1;
    final int MULTIPLICATION_MODE = 2;
    final int DIVISION_MODE = 3;
    // Mode is addition mode by default
    int mode = ADDITION_MODE;
    int nextMode = 0;
    final int REGULAR_MODE = 0;
    final int INTVAL_MODE = 1;
    final int SIGN_MODE = 2;
    final int NO_ZERO_MODE = 3;
    int endMode = REGULAR_MODE;
    boolean attackRoutine = false;
    String attackData = "";
    Float total = 0.0f;
    for (int i = 0; i < str.length(); ++i) {
        valString += str.substring(i, i + 1);
        if ((i == (str.length() - 1)) || ((delimiter.lastIndexOf(str.charAt(i)) > -1) && (i > 0) && (str.charAt(i - 1) != '.'))) {
            if (delimiter.lastIndexOf(str.charAt(i)) > -1) {
                valString = valString.substring(0, valString.length() - 1);
            }
            if (i < str.length()) {
                // Deal with .TRUNC
                if (valString.endsWith(".TRUNC")) {
                    if (attackRoutine) {
                        Logging.errorPrint("Math Mode Error: Not allowed to use .TRUNC in Attack Mode.");
                    } else {
                        valString = String.valueOf(Float.valueOf(mathMode(valString.substring(0, valString.length() - 6), aPC)).intValue());
                    }
                }
                // Deal with .INTVAL
                if (valString.endsWith(".INTVAL")) {
                    if (attackRoutine) {
                        Logging.errorPrint("Math Mode Error: Using .INTVAL in Attack Mode.");
                    } else {
                        valString = mathMode(valString.substring(0, valString.length() - 7), aPC);
                    }
                    endMode = INTVAL_MODE;
                }
                // Deal with .SIGN
                if (valString.endsWith(".SIGN")) {
                    valString = mathMode(valString.substring(0, valString.length() - 5), aPC);
                    endMode = SIGN_MODE;
                }
                // Deal with .NOZERO
                if (valString.endsWith(".NOZERO")) {
                    valString = mathMode(valString.substring(0, valString.length() - 7), aPC);
                    endMode = NO_ZERO_MODE;
                }
                // Set the next mode based on the mathematical sign
                if ((!str.isEmpty()) && (str.charAt(i) == '+')) {
                    nextMode = ADDITION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '-')) {
                    nextMode = SUBTRACTION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '*')) {
                    nextMode = MULTIPLICATION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '/')) {
                    nextMode = DIVISION_MODE;
                }
                StringWriter sWriter = new StringWriter();
                BufferedWriter aWriter = new BufferedWriter(sWriter);
                replaceTokenSkipMath(aPC, valString, aWriter);
                sWriter.flush();
                try {
                    aWriter.flush();
                } catch (IOException e) {
                    Logging.errorPrint("Failed to flush oputput in MathMode.", e);
                }
                final String bString = sWriter.toString();
                try {
                    // Float values
                    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US);
                    DecimalFormat decimalFormat = new DecimalFormat("#,##0.##", decimalFormatSymbols);
                    valString = String.valueOf(decimalFormat.parse(bString));
                } catch (ParseException e) {
                    // String values
                    valString = bString;
                }
                if ((!attackRoutine) && Pattern.matches("^([-+]\\d+/)*[-+]\\d+$", valString)) {
                    attackRoutine = true;
                    attackData = valString;
                    valString = "";
                }
            }
            try {
                if (!valString.isEmpty()) {
                    if (attackRoutine) {
                        StringTokenizer bTok = new StringTokenizer(attackData, "/");
                        if (bTok.countTokens() > 0) {
                            String newAttackData = "";
                            while (bTok.hasMoreTokens()) {
                                final String bString = bTok.nextToken();
                                float bf = Float.parseFloat(bString);
                                float vf = Float.parseFloat(valString);
                                switch(mode) {
                                    case ADDITION_MODE:
                                        float addf = bf + vf;
                                        newAttackData += ("/+" + Integer.toString((int) addf));
                                        break;
                                    case SUBTRACTION_MODE:
                                        float subf = bf - vf;
                                        newAttackData += ("/+" + Integer.toString((int) subf));
                                        break;
                                    case MULTIPLICATION_MODE:
                                        float multf = bf * vf;
                                        newAttackData += ("/+" + Integer.toString((int) multf));
                                        break;
                                    case DIVISION_MODE:
                                        float divf = bf / vf;
                                        newAttackData += ("/+" + Integer.toString((int) divf));
                                        break;
                                    default:
                                        Logging.errorPrint("In mathMode the mode " + mode + " is unsupported.");
                                        break;
                                }
                            }
                            attackData = newAttackData.substring(1).replaceAll(Pattern.quote("+-"), "-");
                        }
                    } else {
                        switch(mode) {
                            case ADDITION_MODE:
                                total = (float) (total.doubleValue() + Double.parseDouble(valString));
                                break;
                            case SUBTRACTION_MODE:
                                total = (float) (total.doubleValue() - Double.parseDouble(valString));
                                break;
                            case MULTIPLICATION_MODE:
                                total = (float) (total.doubleValue() * Double.parseDouble(valString));
                                break;
                            case DIVISION_MODE:
                                total = (float) (total.doubleValue() / Double.parseDouble(valString));
                                break;
                            default:
                                Logging.errorPrint("In mathMode the mode " + mode + " is unsupported.");
                                break;
                        }
                    }
                }
            } catch (NumberFormatException exc) {
                StringWriter sWriter = new StringWriter();
                BufferedWriter aWriter = new BufferedWriter(sWriter);
                replaceTokenSkipMath(aPC, str, aWriter);
                sWriter.flush();
                try {
                    aWriter.flush();
                } catch (IOException e) {
                    Logging.errorPrint("Math Mode Error: Could not flush output.");
                }
                return sWriter.toString();
            }
            mode = nextMode;
            // Set the nextMode back to the default
            nextMode = ADDITION_MODE;
            valString = "";
        }
    }
    if (attackRoutine) {
        return attackData;
    }
    if (endMode == INTVAL_MODE) {
        return Integer.toString(total.intValue());
    }
    if (endMode == SIGN_MODE) {
        return Delta.toString(total.intValue());
    }
    if (endMode == NO_ZERO_MODE) {
        final int totalIntValue = total.intValue();
        if (totalIntValue == 0) {
            return "";
        }
        return Delta.toString(totalIntValue);
    }
    return total.toString();
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) StringTokenizer(java.util.StringTokenizer) StringWriter(java.io.StringWriter) ParseException(java.text.ParseException)

Example 33 with DecimalFormatSymbols

use of java.text.DecimalFormatSymbols in project Settler by EmhyrVarEmreis.

the class JsonDoubleCurrencySerializer method getFormat.

public static DecimalFormat getFormat() {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    symbols.setGroupingSeparator(' ');
    DecimalFormat numFormat = new DecimalFormat();
    numFormat.setGroupingUsed(true);
    numFormat.setMinimumFractionDigits(2);
    numFormat.setMaximumFractionDigits(2);
    numFormat.setDecimalFormatSymbols(symbols);
    return numFormat;
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat)

Example 34 with DecimalFormatSymbols

use of java.text.DecimalFormatSymbols in project pcgen by PCGen.

the class GoldToken method getToken.

/**
	 * @see pcgen.io.exporttoken.Token#getToken(java.lang.String, pcgen.core.PlayerCharacter, pcgen.io.ExportHandler)
	 */
@Override
public String getToken(String tokenSource, PlayerCharacter pc, ExportHandler eh) {
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US);
    NumberFormat decimalFormat = new DecimalFormat("#,##0.##", decimalFormatSymbols);
    return decimalFormat.format(getGoldToken(pc));
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) NumberFormat(java.text.NumberFormat)

Example 35 with DecimalFormatSymbols

use of java.text.DecimalFormatSymbols in project Asqatasun by Asqatasun.

the class ContrastChecker method checkDomElements.

/**
     * 
     * @param sspHandler
     * @param domElements
     * @param testSolutionHandler
     * 
     * @throws ContrastCheckerParseResultException
     */
private void checkDomElements(SSPHandler sspHandler, Collection<DomElement> domElements, TestSolutionHandler testSolutionHandler) throws ContrastCheckerParseResultException {
    for (DomElement domElement : domElements) {
        // to "-1"
        if (isElementPartOfTheScope(domElement)) {
            String bgColor = domElement.getBgColor();
            String fgColor = domElement.getFgColor();
            if (ContrastHelper.isColorTestable(fgColor) && ContrastHelper.isColorTestable(bgColor)) {
                elementCounter++;
                Double contrast = ContrastHelper.getConstrastRatio(fgColor, bgColor);
                if (contrast < contrastRatio) {
                    LOGGER.debug(" cssPath " + domElement.getPath() + " " + +contrast);
                    DecimalFormatSymbols decimalSymbol = new DecimalFormatSymbols(Locale.getDefault());
                    decimalSymbol.setDecimalSeparator('.');
                    TestSolution elementSolution = createRemarkOnBadContrastElement(sspHandler, domElement, new DecimalFormat("#.00", decimalSymbol).format(contrast));
                    testSolutionHandler.addTestSolution(elementSolution);
                } else {
                    LOGGER.debug(" good luminosity " + domElement.getPath() + " " + +contrast);
                }
            } else {
                elementCounter++;
                createNmiRemarkForManualCheckElement(sspHandler, domElement);
                testSolutionHandler.addTestSolution(TestSolution.NEED_MORE_INFO);
                LOGGER.debug(" nmi " + domElement.getPath());
            }
        }
    }
}
Also used : DomElement(org.asqatasun.rules.domelement.DomElement) DecimalFormatSymbols(java.text.DecimalFormatSymbols) TestSolution(org.asqatasun.entity.audit.TestSolution) DecimalFormat(java.text.DecimalFormat)

Aggregations

DecimalFormatSymbols (java.text.DecimalFormatSymbols)133 DecimalFormat (java.text.DecimalFormat)93 NumberFormat (java.text.NumberFormat)14 Locale (java.util.Locale)13 ParseException (java.text.ParseException)8 BigDecimal (java.math.BigDecimal)7 Currency (java.util.Currency)7 ObjectInputStream (java.io.ObjectInputStream)6 Test (org.junit.Test)6 IOException (java.io.IOException)5 ParsePosition (java.text.ParsePosition)5 BufferedChecksumIndexInput (org.apache.lucene.store.BufferedChecksumIndexInput)5 ChecksumIndexInput (org.apache.lucene.store.ChecksumIndexInput)5 IndexInput (org.apache.lucene.store.IndexInput)5 BytesRefBuilder (org.apache.lucene.util.BytesRefBuilder)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ObjectOutputStream (java.io.ObjectOutputStream)4 BytesRef (org.apache.lucene.util.BytesRef)4 ArrayList (java.util.ArrayList)3