Search in sources :

Example 26 with NumberFormat

use of java.text.NumberFormat in project head by mifos.

the class Money method toString.

public String toString(Short digitsAfterDecimal) {
    // FIXME string formating based on Accounting rule should be done in
    // MoneyUtil class
    // only string representation of BigDecimal should be returned here
    double doubleValue = amount.doubleValue();
    String format = "%." + digitsAfterDecimal.toString() + "f";
    String formatStr = String.format(Locale.ENGLISH, format, 0.0);
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
    DecimalFormat decimalFormat = null;
    if (numberFormat instanceof DecimalFormat) {
        decimalFormat = ((DecimalFormat) numberFormat);
        decimalFormat.applyPattern(formatStr);
        return decimalFormat.format(doubleValue);
    }
    return numberFormat.format(doubleValue);
}
Also used : DecimalFormat(java.text.DecimalFormat) NumberFormat(java.text.NumberFormat)

Example 27 with NumberFormat

use of java.text.NumberFormat in project plaid by nickbutcher.

the class PlayerActivity method bindPlayer.

void bindPlayer() {
    if (player == null)
        return;
    final Resources res = getResources();
    final NumberFormat nf = NumberFormat.getInstance();
    Glide.with(this).load(player.getHighQualityAvatarUrl()).placeholder(R.drawable.avatar_placeholder).transform(circleTransform).into(avatar);
    playerName.setText(player.name.toLowerCase());
    if (!TextUtils.isEmpty(player.bio)) {
        DribbbleUtils.parseAndSetText(bio, player.bio);
    } else {
        bio.setVisibility(View.GONE);
    }
    shotCount.setText(res.getQuantityString(R.plurals.shots, player.shots_count, nf.format(player.shots_count)));
    if (player.shots_count == 0) {
        shotCount.setCompoundDrawablesRelativeWithIntrinsicBounds(null, getDrawable(R.drawable.avd_no_shots), null, null);
    }
    setFollowerCount(player.followers_count);
    likesCount.setText(res.getQuantityString(R.plurals.likes, player.likes_count, nf.format(player.likes_count)));
    // load the users shots
    dataManager = new PlayerShotsDataManager(this, player) {

        @Override
        public void onDataLoaded(List<Shot> data) {
            if (data != null && data.size() > 0) {
                if (adapter.getDataItemCount() == 0) {
                    loading.setVisibility(View.GONE);
                    ViewUtils.setPaddingTop(shots, likesCount.getBottom());
                }
                adapter.addAndResort(data);
            }
        }
    };
    adapter = new FeedAdapter(this, dataManager, columns, PocketUtils.isPocketInstalled(this));
    shots.setAdapter(adapter);
    shots.setItemAnimator(new SlideInItemAnimator());
    shots.setVisibility(View.VISIBLE);
    layoutManager = new GridLayoutManager(this, columns);
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

        @Override
        public int getSpanSize(int position) {
            return adapter.getItemColumnSpan(position);
        }
    });
    shots.setLayoutManager(layoutManager);
    shots.addOnScrollListener(new InfiniteScrollListener(layoutManager, dataManager) {

        @Override
        public void onLoadMore() {
            dataManager.loadData();
        }
    });
    shots.setHasFixedSize(true);
    // forward on any clicks above the first item in the grid (i.e. in the paddingTop)
    // to 'pass through' to the view behind
    shots.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int firstVisible = layoutManager.findFirstVisibleItemPosition();
            if (firstVisible > 0)
                return false;
            // if no data loaded then pass through
            if (adapter.getDataItemCount() == 0) {
                return container.dispatchTouchEvent(event);
            }
            final RecyclerView.ViewHolder vh = shots.findViewHolderForAdapterPosition(0);
            if (vh == null)
                return false;
            final int firstTop = vh.itemView.getTop();
            if (event.getY() < firstTop) {
                return container.dispatchTouchEvent(event);
            }
            return false;
        }
    });
    // check if following
    if (dataManager.getDribbblePrefs().isLoggedIn()) {
        if (player.id == dataManager.getDribbblePrefs().getUserId()) {
            TransitionManager.beginDelayedTransition(container);
            follow.setVisibility(View.GONE);
            ViewUtils.setPaddingTop(shots, container.getHeight() - follow.getHeight() - ((ViewGroup.MarginLayoutParams) follow.getLayoutParams()).bottomMargin);
        } else {
            final Call<Void> followingCall = dataManager.getDribbbleApi().following(player.id);
            followingCall.enqueue(new Callback<Void>() {

                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    following = response.isSuccessful();
                    if (!following)
                        return;
                    TransitionManager.beginDelayedTransition(container);
                    follow.setText(R.string.following);
                    follow.setActivated(true);
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                }
            });
        }
    }
    if (player.shots_count > 0) {
        // kick off initial load
        dataManager.loadData();
    } else {
        loading.setVisibility(View.GONE);
    }
}
Also used : PlayerShotsDataManager(io.plaidapp.data.api.dribbble.PlayerShotsDataManager) ImageView(android.widget.ImageView) BindView(butterknife.BindView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) MotionEvent(android.view.MotionEvent) GridLayoutManager(android.support.v7.widget.GridLayoutManager) SlideInItemAnimator(io.plaidapp.ui.recyclerview.SlideInItemAnimator) Resources(android.content.res.Resources) Shot(io.plaidapp.data.api.dribbble.model.Shot) InfiniteScrollListener(io.plaidapp.ui.recyclerview.InfiniteScrollListener) NumberFormat(java.text.NumberFormat)

Example 28 with NumberFormat

use of java.text.NumberFormat in project openhab1-addons by openhab.

the class KNXCoreTypeMapper method toType.

/*
     * (non-Javadoc)
     *
     * @see org.openhab.binding.knx.config.KNXTypeMapper#toType(tuwien.auto.calimero.datapoint.Datapoint, byte[])
     */
@Override
public Type toType(Datapoint datapoint, byte[] data) {
    try {
        DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
        translator.setData(data);
        String value = translator.getValue();
        String id = translator.getType().getID();
        logger.trace("toType datapoint DPT = " + datapoint.getDPT());
        int mainNumber = getMainNumber(id);
        if (mainNumber == -1) {
            logger.debug("toType: couldn't identify mainnumber in dptID: {}.", id);
            return null;
        }
        int subNumber = getSubNumber(id);
        if (subNumber == -1) {
            logger.debug("toType: couldn't identify sub number in dptID: {}.", id);
            return null;
        }
        /*
             * Following code section deals with specific mapping of values from KNX to openHAB types were the String
             * received from the DPTXlator is not sufficient to set the openHAB type or has bugs
             */
        switch(mainNumber) {
            case 1:
                DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
                switch(subNumber) {
                    case 8:
                        return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
                    case 9:
                        return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                    case 10:
                        return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
                    case 19:
                        return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                    case 22:
                        return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
                    default:
                        return translatorBoolean.getValueBoolean() ? OnOffType.ON : OnOffType.OFF;
                }
            case 2:
                DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
                int decValue = (translator1BitControlled.getControlBit() ? 2 : 0) + (translator1BitControlled.getValueBit() ? 1 : 0);
                return new DecimalType(decValue);
            case 3:
                DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
                if (translator3BitControlled.getStepCode() == 0) {
                    /*
                         * there is no STOP for a IncreaseDecreaseType, so we are just using an INCREASE.
                         * It is up to the binding to recognize that a start/stop-dimming is in progress and
                         * stop the dimming accordingly.
                         */
                    logger.debug("toType: KNX DPT_Control_Dimming: break received.");
                    return IncreaseDecreaseType.INCREASE;
                }
                switch(subNumber) {
                    case 7:
                        return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE : IncreaseDecreaseType.DECREASE;
                    case 8:
                        return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
                }
            case 14:
                /*
                     * FIXME: Workaround for a bug in Calimero / Openhab DPTXlator4ByteFloat.makeString(): is using a
                     * locale when
                     * translating a Float to String. It could happen the a ',' is used as separator, such as
                     * 3,14159E20.
                     * Openhab's DecimalType expects this to be in US format and expects '.': 3.14159E20.
                     * There is no issue with DPTXlator2ByteFloat since calimero is using a non-localized translation
                     * there.
                     */
                DPTXlator4ByteFloat translator4ByteFloat = (DPTXlator4ByteFloat) translator;
                Float f = translator4ByteFloat.getValueFloat();
                if (Math.abs(f) < 100000) {
                    value = String.valueOf(f);
                } else {
                    NumberFormat dcf = NumberFormat.getInstance(Locale.US);
                    if (dcf instanceof DecimalFormat) {
                        ((DecimalFormat) dcf).applyPattern("0.#####E0");
                    }
                    value = dcf.format(f);
                }
                break;
            case 18:
                DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
                int decimalValue = translatorSceneControl.getSceneNumber();
                if (value.startsWith("learn")) {
                    decimalValue += 0x80;
                }
                value = String.valueOf(decimalValue);
                break;
            case 19:
                DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
                if (translatorDateTime.isFaultyClock()) {
                    // Not supported: faulty clock
                    logger.debug("toType: KNX clock msg ignored: clock faulty bit set, which is not supported");
                    return null;
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
                    // Not supported: "/1/1" (month and day without year)
                    logger.debug("toType: KNX clock msg ignored: no year, but day and month, which is not supported");
                    return null;
                } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
                    // Not supported: "1900" (year without month and day)
                    logger.debug("toType: KNX clock msg ignored: no day and month, but year, which is not supported");
                    return null;
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE) && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Not supported: No year, no date and no time
                    logger.debug("toType: KNX clock msg ignored: no day and month or year, which is not supported");
                    return null;
                }
                Calendar cal = Calendar.getInstance();
                if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Pure date format, no time information
                    cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Pure time format, no date information
                    cal.clear();
                    cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
                    cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
                    cal.set(Calendar.SECOND, translatorDateTime.getSecond());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR) && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
                    // Date format and time information
                    cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
                    value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
                    return DateTimeType.valueOf(value);
                }
                break;
        }
        Class<? extends Type> typeClass = toTypeClass(id);
        if (typeClass == null) {
            return null;
        }
        if (typeClass.equals(PercentType.class)) {
            return PercentType.valueOf(value.split(" ")[0]);
        }
        if (typeClass.equals(DecimalType.class)) {
            return DecimalType.valueOf(value.split(" ")[0]);
        }
        if (typeClass.equals(StringType.class)) {
            return StringType.valueOf(value);
        }
        if (typeClass.equals(DateTimeType.class)) {
            String date = formatDateTime(value, datapoint.getDPT());
            if ((date == null) || (date.isEmpty())) {
                logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);
                return null;
            } else {
                return DateTimeType.valueOf(date);
            }
        }
        if (typeClass.equals(HSBType.class)) {
            // value has format of "r:<red value> g:<green value> b:<blue value>"
            int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);
            int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);
            int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);
            Color color = new Color(r, g, b);
            return new HSBType(color);
        }
    } catch (KNXFormatException kfe) {
        logger.info("Translator couldn't parse data for datapoint type '{}' (KNXFormatException).", datapoint.getDPT());
    } catch (KNXIllegalArgumentException kiae) {
        logger.info("Translator couldn't parse data for datapoint type '{}' (KNXIllegalArgumentException).", datapoint.getDPT());
    } catch (KNXException e) {
        logger.warn("Failed creating a translator for datapoint type '{}'.", datapoint.getDPT(), e);
    }
    return null;
}
Also used : KNXException(tuwien.auto.calimero.exception.KNXException) DPTXlatorDateTime(tuwien.auto.calimero.dptxlator.DPTXlatorDateTime) KNXIllegalArgumentException(tuwien.auto.calimero.exception.KNXIllegalArgumentException) DecimalFormat(java.text.DecimalFormat) Calendar(java.util.Calendar) Color(java.awt.Color) DPTXlatorString(tuwien.auto.calimero.dptxlator.DPTXlatorString) Datapoint(tuwien.auto.calimero.datapoint.Datapoint) DPTXlatorBoolean(tuwien.auto.calimero.dptxlator.DPTXlatorBoolean) DPTXlator2ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat) DPTXlator4ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat) DPTXlatorSceneControl(tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl) DPTXlator(tuwien.auto.calimero.dptxlator.DPTXlator) DecimalType(org.openhab.core.library.types.DecimalType) DPTXlator3BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled) DPTXlator4ByteFloat(tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat) KNXFormatException(tuwien.auto.calimero.exception.KNXFormatException) DPTXlator1BitControlled(tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled) SimpleDateFormat(java.text.SimpleDateFormat) HSBType(org.openhab.core.library.types.HSBType) NumberFormat(java.text.NumberFormat)

Example 29 with NumberFormat

use of java.text.NumberFormat in project jodd by oblac.

the class LocaleUtil method getNumberFormat.

/**
	 * Returns cached <code>NumberFormat</code> instance for specified locale.
	 */
public static NumberFormat getNumberFormat(Locale locale) {
    LocaleData localeData = lookupLocaleData(locale);
    NumberFormat nf = localeData.numberFormat;
    if (nf == null) {
        nf = NumberFormat.getInstance(locale);
        localeData.numberFormat = nf;
    }
    return nf;
}
Also used : NumberFormat(java.text.NumberFormat)

Example 30 with NumberFormat

use of java.text.NumberFormat in project android-saripaar by ragunathjawahar.

the class AbstractNumberValidator method getFormat.

/**
     * <p>Returns a <code>NumberFormat</code> for the specified <i>pattern</i>
     *    and/or <code>Locale</code>.</p>
     *
     * @param pattern The pattern used to validate the value against or
     *        <code>null</code> to use the default for the <code>Locale</code>.
     * @param locale The locale to use for the currency format, system default if null.
     * @return The <code>NumberFormat</code> to created.
     */
protected Format getFormat(String pattern, Locale locale) {
    NumberFormat formatter = null;
    boolean usePattern = (pattern != null && pattern.length() > 0);
    if (!usePattern) {
        formatter = (NumberFormat) getFormat(locale);
    } else if (locale == null) {
        formatter = new DecimalFormat(pattern);
    } else {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
        formatter = new DecimalFormat(pattern, symbols);
    }
    if (determineScale(formatter) == 0) {
        formatter.setParseIntegerOnly(true);
    }
    return formatter;
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) NumberFormat(java.text.NumberFormat)

Aggregations

NumberFormat (java.text.NumberFormat)429 DecimalFormat (java.text.DecimalFormat)87 BigDecimal (java.math.BigDecimal)23 ArrayList (java.util.ArrayList)23 HashMap (java.util.HashMap)23 Locale (java.util.Locale)22 Map (java.util.Map)18 Test (org.junit.Test)17 ParseException (java.text.ParseException)15 DecimalFormatSymbols (java.text.DecimalFormatSymbols)14 JFreeChart (org.jfree.chart.JFreeChart)13 XYSeries (org.jfree.data.xy.XYSeries)11 XYSeriesCollection (org.jfree.data.xy.XYSeriesCollection)11 Intent (android.content.Intent)10 ParsePosition (java.text.ParsePosition)10 View (android.view.View)8 TextView (android.widget.TextView)8 Paint (android.graphics.Paint)7 Rect (android.graphics.Rect)6 IOException (java.io.IOException)6