Java Code Examples for java.text.NumberFormat#setMaximumIntegerDigits()

The following examples show how to use java.text.NumberFormat#setMaximumIntegerDigits() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MDLV2000Writer.java    From ReactionDecoder with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Formats a float to fit into the connectiontable and changes it to a
 * String.
 *
 * @param fl The float to be formated
 * @return The String to be written into the connectiontable
 */
protected static String formatMDLFloat(float fl) {
    String s = "", fs = "";
    int l;
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
    nf.setMinimumIntegerDigits(1);
    nf.setMaximumIntegerDigits(4);
    nf.setMinimumFractionDigits(4);
    nf.setMaximumFractionDigits(4);
    nf.setGroupingUsed(false);
    if (Double.isNaN(fl) || Double.isInfinite(fl)) {
        s = "0.0000";
    } else {
        s = nf.format(fl);
    }
    l = 10 - s.length();
    for (int f = 0; f < l; f++) {
        fs += " ";
    }
    fs += s;
    return fs;
}
 
Example 2
Source File: StrUtil.java    From kAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 将double类型数据转换为百分比格式,并保留小数点前IntegerDigits位和小数点后FractionDigits位
 *
 * @param d
 * @param integerDigits  当为0或负数时不设置保留位数
 * @param fractionDigits 当为0或负数时不设置保留位数
 * @return
 */
public static String getPercentFormat(double d, int integerDigits, int fractionDigits) {
    NumberFormat nf = NumberFormat.getPercentInstance();
    if (integerDigits > 0) {
        nf.setMaximumIntegerDigits(integerDigits);//小数点前保留几位
    }
    if (fractionDigits > 0) {
        nf.setMinimumFractionDigits(fractionDigits);// 小数点后保留几位
    }
    String str = nf.format(d);
    if (d > 0) {
        return "+" + str;
    } else if (d == 0) {
        return 0 + "";
    } else {
        return str;
    }
}
 
Example 3
Source File: BasicFormatter.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public NumberFormat getNumberFormatter(int pDigits) {
    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumFractionDigits(0);
    f.setMinimumFractionDigits(0);
    if (pDigits < 10) {
        f.setMaximumIntegerDigits(1);
    } else if (pDigits < 100) {
        f.setMaximumIntegerDigits(2);
    } else if (pDigits < 1000) {
        f.setMaximumIntegerDigits(3);
    } else if (pDigits < 10000) {
        f.setMaximumIntegerDigits(4);
    } else {
        f.setMaximumIntegerDigits(5);
    }
    return f;
}
 
Example 4
Source File: MDLV2000RXNWriter.java    From ReactionDecoder with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Formats an int to fit into the connection table and changes it to a
 * String.
 *
 * @param i The int to be formated
 * @param l Length of the String
 * @return The String to be written into the connection table
 */
private String formatMDLInt(int i, int l) {
    String s = "", fs = "";
    NumberFormat nf = getNumberInstance(ENGLISH);
    nf.setParseIntegerOnly(true);
    nf.setMinimumIntegerDigits(1);
    nf.setMaximumIntegerDigits(l);
    nf.setGroupingUsed(false);
    s = nf.format(i);
    l -= s.length();
    for (int f = 0; f < l; f++) {
        fs += " ";
    }
    fs += s;
    return fs;
}
 
Example 5
Source File: DateTimeComponents.java    From biweekly with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Converts the date-time components to a string.
 * @param includeTime true to include the time portion, false not to
 * @param extended true to use extended format, false to use basic
 * @return the date string
 */
public String toString(boolean includeTime, boolean extended) {
	NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
	nf.setMinimumIntegerDigits(2);
	nf.setMaximumIntegerDigits(2);
	String dash = extended ? "-" : "";
	String colon = extended ? ":" : "";
	String z = utc ? "Z" : "";

	StringBuilder sb = new StringBuilder();
	sb.append(year).append(dash).append(nf.format(month)).append(dash).append(nf.format(date));
	if (includeTime) {
		sb.append("T").append(nf.format(hour)).append(colon).append(nf.format(minute)).append(colon).append(nf.format(second)).append(z);
	}
	return sb.toString();
}
 
Example 6
Source File: NthIncludedDayTrigger.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the fire time for the <CODE>NthIncludedDayTrigger</CODE> as a
 * string with the format &quot;HH:MM[:SS]&quot;, with HH representing the 
 * 24-hour clock hour of the fire time. Seconds are optional and their 
 * inclusion depends on whether or not they were provided to 
 * {@link #setFireAtTime(String)}. 
 * 
 * @return the fire time for the trigger
 * @see #setFireAtTime(String)
 */
public String getFireAtTime() {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumIntegerDigits(2);
    format.setMinimumIntegerDigits(2);
    format.setMaximumFractionDigits(0);
    
    return format.format(this.fireAtHour) + ":" + 
           format.format(this.fireAtMinute) + ":" +
           format.format(this.fireAtSecond);
}
 
Example 7
Source File: NumberUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Write a number into a string value.
 *
 * @param value          the number to write
 * @param integerDigits  maximal number of integer digits
 * @param fractionDigits maximal number of fraction digits
 * @param locale         locale for decimal separator (using {@link Locale#ENGLISH} if null)
 * @return the formatted number
 */
public static String printNumber(Number value, int integerDigits, int fractionDigits, Locale locale) {
    if (value == null) return null;
    NumberFormat format = NumberFormat.getNumberInstance((locale != null) ? locale : Locale.ENGLISH);
    format.setMaximumIntegerDigits(integerDigits);
    format.setMaximumFractionDigits(fractionDigits);
    format.setMinimumFractionDigits(0);
    format.setGroupingUsed(false);
    return format.format(value);
}
 
Example 8
Source File: ChangeTestWeightCommandFactory.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param user
 * @param locale
 * @param testList
 * @param referentialKey
 * @return 
 *      an initialised instance of ChangeTestWeightCommand
 */
public ChangeTestWeightCommand getChangeTestWeightCommand(
        User user, 
        Locale locale,
        Collection<Test> testList, 
        String referentialKey) {
    Map<String, String> userTestWeight = new HashMap<String, String>();
    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(1);
    nf.setMaximumIntegerDigits(1);
    nf.setMinimumIntegerDigits(1);
    for (OptionElement oe : optionElementDataService.getOptionElementFromUserAndFamilyCode(user, referentialKey+"_"+optionFamilyCodeStr)) {
        userTestWeight.put(
                oe.getOption().getCode(), 
                nf.format(Double.valueOf(oe.getValue())));
    }
    for (Test test : testList) {
        if (!userTestWeight.containsKey(test.getCode())) {
            userTestWeight.put(test.getCode(), "");
        }
    }
    
    ChangeTestWeightCommand changeTestWeightCommand = 
            new ChangeTestWeightCommand();
    changeTestWeightCommand.setTestWeightMap(userTestWeight);
    return changeTestWeightCommand;
}
 
Example 9
Source File: NumberColumnFormatter.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
/** Returns a formatter that prints floating point numbers with all precision */
public static NumberColumnFormatter floatingPointDefault() {
  NumberFormat format =
      new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.getDefault()));
  format.setMaximumFractionDigits(340);
  format.setMaximumIntegerDigits(340);
  format.setGroupingUsed(false);
  return new NumberColumnFormatter(format);
}
 
Example 10
Source File: NumberColumnFormatter.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
/** Returns a formatter that prints floating point numbers with all precision */
public static NumberColumnFormatter floatingPointDefault() {
  NumberFormat format =
      new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.getDefault()));
  format.setMaximumFractionDigits(340);
  format.setMaximumIntegerDigits(340);
  format.setGroupingUsed(false);
  return new NumberColumnFormatter(format);
}
 
Example 11
Source File: Slic3rPrints.java    From BowlerStudio with GNU General Public License v3.0 5 votes vote down vote up
public NumberFormat getNumFormat(int numInts, int numDec){
	NumberFormat x = NumberFormat.getNumberInstance();
	x.setMaximumFractionDigits(numDec);
	x.setMinimumFractionDigits(numDec);
	x.setMaximumIntegerDigits(numInts);
	x.setMinimumIntegerDigits(numInts);
	return x;
}
 
Example 12
Source File: Slic3rAll.java    From BowlerStudio with GNU General Public License v3.0 5 votes vote down vote up
public NumberFormat getNumFormat(int numInts, int numDec){
	NumberFormat x = NumberFormat.getNumberInstance();
	x.setMaximumFractionDigits(numDec);
	x.setMinimumFractionDigits(numDec);
	x.setMaximumIntegerDigits(numInts);
	x.setMinimumIntegerDigits(numInts);
	return x;
}
 
Example 13
Source File: AdvancedSecurityPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public AdvancedSecurityPanel(Binding binding, ConfigVersion cfgVersion) {
    this.binding = binding;
    this.cfgVersion = cfgVersion;
    
    freshnessff = new DefaultFormatterFactory();
    NumberFormat freshnessFormat = NumberFormat.getIntegerInstance();
    freshnessFormat.setGroupingUsed(false);
    NumberFormatter freshnessFormatter = new NumberFormatter(freshnessFormat);
    freshnessFormat.setMaximumIntegerDigits(8);
    freshnessFormatter.setCommitsOnValidEdit(true);
    freshnessFormatter.setMinimum(0);
    freshnessFormatter.setMaximum(99999999);
    freshnessff.setDefaultFormatter(freshnessFormatter);
            
    skewff = new DefaultFormatterFactory();
    NumberFormat skewFormat = NumberFormat.getIntegerInstance();
    skewFormat.setGroupingUsed(false);
    NumberFormatter skewFormatter = new NumberFormatter(skewFormat);
    skewFormat.setMaximumIntegerDigits(8);
    skewFormatter.setCommitsOnValidEdit(true);
    skewFormatter.setMinimum(0);
    skewFormatter.setMaximum(99999999);
    skewff.setDefaultFormatter(skewFormatter);

    initComponents();
    
    sync();
}
 
Example 14
Source File: GraphEditorWindow.java    From slick2d-maven with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert a float to a string format
 * 
 * @param f The float to convert 
 * @return The string formatted from the float
 */
private String convertFloat(float f) {
	NumberFormat format = NumberFormat.getInstance();
	format.setMinimumFractionDigits(2);
	format.setMaximumFractionDigits(2);
	format.setMinimumIntegerDigits(1);
	format.setMaximumIntegerDigits(5);
	return format.format(f);
}
 
Example 15
Source File: UUIDServiceRedisImpl.java    From redis_util with Apache License 2.0 5 votes vote down vote up
private Long createUUID(Long num, String day, Integer length) {
    String id = String.valueOf(num);
    if (id.length() < length) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(length);
        nf.setMinimumIntegerDigits(length);
        id = nf.format(num);
    }
    return Long.parseLong(day + id);
}
 
Example 16
Source File: CSVUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * According to the 1.7.7 spec If a logical type is invalid, for example a
 * decimal with scale greater than its precision,then implementations should
 * ignore the logical type and use the underlying Avro type.
 */
private static void normalizeNumberFormat(NumberFormat numberFormat, int scale, int precision) {
    if (scale < precision) {
        // write out with the specified precision and scale.
        numberFormat.setMaximumIntegerDigits(precision);
        numberFormat.setMaximumFractionDigits(scale);
        numberFormat.setMinimumFractionDigits(scale);
    }
}
 
Example 17
Source File: NumberUtil.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
/**
 * @todo 私有方法,为parseDouble,parseFloat等提供统一的处理实现
 * @param parseTarget
 * @param maxIntDigits
 * @param minIntDigits
 * @param maxFractionDigits
 * @param minFractionDigits
 * @return
 */
private static Number parseStr(String parseTarget, Integer maxIntDigits, Integer minIntDigits,
		Integer maxFractionDigits, Integer minFractionDigits) {
	if (StringUtil.isBlank(parseTarget)) {
		return null;
	}
	NumberFormat nf = NumberFormat.getInstance();
	try {
		// 最大整数位
		if (maxIntDigits != null) {
			nf.setMaximumIntegerDigits(maxIntDigits.intValue());
		}
		// 最小整数位
		if (minIntDigits != null) {
			nf.setMinimumIntegerDigits(minIntDigits.intValue());
		}

		// 最大小数位
		if (maxFractionDigits != null) {
			nf.setMaximumFractionDigits(maxFractionDigits.intValue());
		}
		// 最小小数位
		if (minFractionDigits != null) {
			nf.setMinimumFractionDigits(minFractionDigits.intValue());
		}
		return nf.parse(parseTarget.replace(",", ""));
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 18
Source File: TingAlbumDetailAdapter.java    From AssistantBySDK with Apache License 2.0 4 votes vote down vote up
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (position == 0) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        //专辑详情
        Glide.with(mContext).load(mAlbum.getCoverUrlMiddle()).into(headerHolder.mIvAlbum);
        headerHolder.mTvAlbumTitle.setText(mAlbum.getAlbumTitle());
        LastUpTrack lastUptrack = mAlbum.getLastUptrack();
        StringBuilder sb = new StringBuilder();
        headerHolder.mTvLastTrack.setText(sb.append("更新至").append(TimeUtils.formatDate(new Date(lastUptrack.getCreatedAt()))).append("  ").append(lastUptrack.getTrackTitle()).toString());
        sb.setLength(0);
        headerHolder.mTvPlayCount.setText(sb.append(StringUtils.formPlayCount(mAlbum.getPlayCount())).append("次播放").toString());
        sb.setLength(0);
        headerHolder.mTvTrackCount.setText(sb.append(mAlbum.getIncludeTrackCount()).append("集").toString());
        //订阅状态
        boolean isSubscribe = mAlbumDao.isSubscribe(mAlbumId);
        headerHolder.mTvSubscribe.setText(isSubscribe ? "已订阅" : "订阅");
        LevelListDrawable ld = (LevelListDrawable) headerHolder.mTvSubscribe.getBackground();
        ld.setLevel(isSubscribe ? 1 : 0);

        if (mHistory != null) {
            headerHolder.mRlHistoryBox.setVisibility(View.VISIBLE);
            sb.setLength(0);
            headerHolder.mTvHistoryTitle.setText(sb.append("继续播放:").append(mHistory.getTrackTitle()).toString());
            sb.setLength(0);
            NumberFormat nf = NumberFormat.getPercentInstance();
            //返回数的整数部分所允许的最大位数
            nf.setMaximumIntegerDigits(3);
            //返回数的小数部分所允许的最大位数
            nf.setMaximumFractionDigits(0);
            headerHolder.mTvProgress.setText(sb.append("已播  ").append(nf.format(mHistory.getBreakPos() / (double) mHistory.getDuration())).toString());
            headerHolder.mIvTingSwitch.setImageLevel((XmlyManager.get().isPlaying() && playTrackId == mHistory.getTrackId()) ? 1 : 0);
        } else {
            headerHolder.mRlHistoryBox.setVisibility(View.GONE);
        }

    } else {
        Track track = mTracks.get(position);
        TrackDetailHolder detailHolder = (TrackDetailHolder) holder;
        detailHolder.mTvTrackTitle.setText(track.getTrackTitle());
        detailHolder.mTvTrackTitle.setTextColor(track.getDataId() == playTrackId
                ? mContext.getResources().getColor(R.color.second_base_color)
                : mContext.getResources().getColor(R.color.new_text_color_first));
        detailHolder.mIvTingSwitch.setImageLevel(0);
        if (track.getDataId() == playTrackId)
            detailHolder.mIvTingSwitch.setImageLevel(XmlyManager.get().isPlaying() ? 1 : 0);
        detailHolder.mTvCreated.setText(TimeUtils.getInstance().getDateString(new Date(track.getCreatedAt())));
        detailHolder.mTvDuration.setText(new SimpleDate().formDuration(track.getDuration()));
    }
}
 
Example 19
Source File: NumberFormatTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @tests java.text.NumberFormat#getMaximumIntegerDigits()
 */
public void test_getMaximumIntegerDigits() {
    NumberFormat format = NumberFormat.getInstance();
    format.setMaximumIntegerDigits(2);
    assertEquals("Wrong result", "23", format.format(123));
}
 
Example 20
Source File: TestSampleIndex.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
     * Create and populate relation in the {@link #namespace}.
     * 
     * @return The #of distinct entries.
     */
    private int loadData(final int scale) {

		final String[] names = new String[] { "John", "Mary", "Saul", "Paul",
				"Leon", "Jane", "Mike", "Mark", "Jill", "Jake", "Alex", "Lucy" };

		final Random rnd = new Random();
		
		// #of distinct instances of each name.
		final int populationSize = Math.max(10, (int) Math.ceil(scale / 10.));
		
		// #of trailing zeros for each name.
		final int nzeros = 1 + (int) Math.ceil(Math.log10(populationSize));
		
//		System.out.println("scale=" + scale + ", populationSize="
//				+ populationSize + ", nzeros=" + nzeros);

		final NumberFormat fmt = NumberFormat.getIntegerInstance();
		fmt.setMinimumIntegerDigits(nzeros);
		fmt.setMaximumIntegerDigits(nzeros);
		fmt.setGroupingUsed(false);
		
        // create the relation.
        final R rel = new R(jnl, namespace, ITx.UNISOLATED, new Properties());
        rel.create();

        // data to insert.
		final E[] a = new E[scale];

		for (int i = 0; i < scale; i++) {

			final String n1 = names[rnd.nextInt(names.length)]
					+ fmt.format(rnd.nextInt(populationSize));

			final String n2 = names[rnd.nextInt(names.length)]
					+ fmt.format(rnd.nextInt(populationSize));

//			System.err.println("i=" + i + ", n1=" + n1 + ", n2=" + n2);
			
			a[i] = new E(n1, n2);
			
        }

		// sort before insert for efficiency.
		Arrays.sort(a,R.primaryKeyOrder.getComparator());
		
        // insert data (the records are not pre-sorted).
        final long ninserts = rel.insert(new ChunkedArrayIterator<E>(a.length, a, null/* keyOrder */));

        // Do commit since not scale-out.
        jnl.commit();

        // should exist as of the last commit point.
        this.rel = (R) jnl.getResourceLocator().locate(namespace,
                ITx.READ_COMMITTED);

        assertNotNull(rel);

        return (int) ninserts;
        
    }