下面列出了java.text.NumberFormat#setRoundingMode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* @param value 需要转换的小数
* @return 省略末尾为0的字符串
*/
public static String convertToOmitLastZeroString(double value) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
/*
* setMinimumFractionDigits设置成2
*
* 如果不这么做,那么当value的值是100.00的时候返回100
*
* 而不是100.00
*/
nf.setMinimumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
// 去掉小数后面的0,如果最后一位是.,则去掉
String s = nf.format(value);
if(s.indexOf(".") > 0){
s = s.replaceAll("0+?$", "");//去掉多余的0
s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
}
return s;
}
public void testPercentageRounding() throws Exception {
NumberFormat nf = NumberFormat.getPercentInstance(Locale.US);
assertEquals("15%", nf.format(0.149));
assertEquals("14%", nf.format(0.142));
nf.setRoundingMode(RoundingMode.UP);
assertEquals("15%", nf.format(0.142));
nf.setRoundingMode(RoundingMode.DOWN);
assertEquals("14%", nf.format(0.149));
nf.setMaximumFractionDigits(1);
// J2ObjC: Was a bad test using 0.149 as input because floating point representation might
// be less than 0.149 and round down to 14.8%.
assertEquals("14.9%", nf.format(0.1491));
}
/**
* Gets a NumberFormat, using the given precision and scale settings.
* Caller must use doParseNumber() to handle trailing garbage in input string.
* @param scale number of digits to the right of the decimal that will be shown
*/
public NumberFormat getNumberFormat(int scale, boolean scaleSpecified) {
// don't use the cached NumberFormat because we are altering it
NumberFormat nf = getFormatProvider(this.locale).getNumberFormat(this.locale);
// We handle numbers longer than their precision with separate logic...
// If we make the following call, it does truncation and rounding on the integer part which we do not desire.
// But we DO want that effect on the fractional part of the number.
// nf.setMaximumIntegerDigits(precision-scale);
nf.setMinimumFractionDigits(scale);
if (scaleSpecified)
nf.setMaximumFractionDigits(scale);
//Changing the rounding mode to HALF_UP for all number type
nf.setRoundingMode(RoundingMode.HALF_UP);
return nf;
}
/**
* ECMA 15.7.4.5 Number.prototype.toFixed (fractionDigits) specialized for int fractionDigits
*
* @param self self reference
* @param fractionDigits how many digits should be after the decimal point, 0 if undefined
*
* @return number in decimal fixed point notation
*/
@SpecializedFunction
public static String toFixed(final Object self, final int fractionDigits) {
if (fractionDigits < 0 || fractionDigits > 20) {
throw rangeError("invalid.fraction.digits", "toFixed");
}
final double x = getNumberValue(self);
if (Double.isNaN(x)) {
return "NaN";
}
if (Math.abs(x) >= 1e21) {
return JSType.toString(x);
}
final NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
format.setMinimumFractionDigits(fractionDigits);
format.setMaximumFractionDigits(fractionDigits);
format.setGroupingUsed(false);
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(x);
}
private static String format(Locale locale, Style style, RoundingMode mode, double number) {
if (locale == null || style == null) {
return String.valueOf(number); // or use a default format
}
NumberFormat nf = NumberFormat.getCompactNumberInstance(locale, style);
if (mode != null) {
nf.setRoundingMode(mode);
}
return nf.format(number);
}
private static String formatNumber(double position) {
if (showOnlyEndPts) {
//Export Version
NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
//return f.valueToString(position);
return df.format(position);
} else {
DecimalFormat formatter = new DecimalFormat();
return formatter.format((int) position);
}
}
private static String formatNumber(double position) {
if (showOnlyEndPts) {
//Export Version
NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
//return f.valueToString(position);
return df.format(position);
} else {
DecimalFormat formatter = new DecimalFormat();
return formatter.format((int) position);
}
}
private String formatAmount(Coin coin, BigInteger amount) {
//String symbol = coin.getSymbol();
String code = coin.getCode();
int decimals = coin.getDecimals();
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(decimals);
format.setMaximumFractionDigits(decimals);
format.setRoundingMode(RoundingMode.UNNECESSARY);
BigDecimal decimal = new BigDecimal(amount);
decimal = decimal.divide(BigDecimal.TEN.pow(decimals));
String value = format.format(decimal);
return /*(symbol == null ? "" : symbol + " ") +*/ value + " " + code;
}
@Test
public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.FLOOR);
String truncated = nf.format(doubleValue);
assertEquals("345", truncated);
}
private static String format(BigDecimal x)
{
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits((x.scale() > 0) ? x.precision() : x.scale());
return formatter.format(x);
}
private String numberFormat(double value, int scale) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(scale);
nf.setRoundingMode(RoundingMode.HALF_EVEN);
/**
* 是否需要用逗号隔开
*/
nf.setGroupingUsed(true);
return nf.format(value);
}
private String format(BigDecimal x)
{
NumberFormat formatter = new DecimalFormat("0.#E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMaximumFractionDigits(6);
return formatter.format(x).replace(",", ".");
}
public static Object formatValue(Object value, String dataFormat){
Object actualValue;
if(value instanceof Date){
if(StringUtils.isBlank(dataFormat))
dataFormat = DateUtils.DATE_TIME;
actualValue = DateUtils.format(dataFormat, (Date)value);
}else if(value instanceof Number && dataFormat != null) {
NumberFormat nf = new DecimalFormat(dataFormat);
nf.setRoundingMode(RoundingMode.HALF_UP);
actualValue = nf.format(value);
}else{
actualValue = value;
}
return actualValue;
}
@Override
protected NumberFormat initialValue() {
NumberFormat format = NumberFormat.getInstance(locale);
format.setParseIntegerOnly(false);
format.setRoundingMode(RoundingMode.CEILING);
return format;
}
private NumberFormat getNumberFormat(CalculateEntry calculateEntry) {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
if (StringUtils.equals(calculateEntry.formatType, CalculateEntry.FORMATTYPE_CURRENCY)) {
numberFormat = NumberFormat.getCurrencyInstance();
return numberFormat;
} else if (StringUtils.equals(calculateEntry.formatType, CalculateEntry.FORMATTYPE_PERCENT)) {
numberFormat = NumberFormat.getPercentInstance();
}
if ((null != calculateEntry.decimal) && (calculateEntry.decimal >= 0)) {
numberFormat.setMaximumFractionDigits(calculateEntry.decimal);
}
return numberFormat;
}
@Test
public void whenUsingNumberFormat_thenValueIsRounded() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.HALF_UP);
String rounded = nf.format(doubleValue);
assertEquals("346", rounded);
}
private NumberFormat adjustCurrencyScale(NumberFormat cf, int scale) {
// We handle numbers longer than their precision with separate logic...
// If we make the following call, it does truncation and rounding on the integer part which we do not desire.
// But we DO want that effect on the fractional part of the number.
// cf.setMaximumIntegerDigits(precision-scale);
cf.setMinimumFractionDigits(scale);
cf.setMaximumFractionDigits(scale);
//Changing the rounding mode to Half_UP to be consistent throughout the app
cf.setRoundingMode(RoundingMode.HALF_UP);
return cf;
}
private static NumberFormat createNumberFormatter(Integer scale, RoundingMode mode) {
NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(scale);
format.setMaximumFractionDigits(scale);
format.setRoundingMode(mode);
return format;
}
private static void showTNTblastChance(Explosion e){
ExplosionAccessor eAccess = (ExplosionAccessor) e;
double randMax = 0.6F * eAccess.getPower();
double total = 0;
boolean fullyBlownUp = false;
boolean first = true;
int rays = 0;
for(float f3 : chances){
rays++;
double calc = f3 - randMax;
if(calc > 0) fullyBlownUp = true;
double chancePerRay = (Math.abs(calc) / randMax);
if(!fullyBlownUp){
if(first){
first = false;
total = chancePerRay;
}else {
total = total * chancePerRay;
}
}
}
if(fullyBlownUp) total = 0;
double chance = 1 - total;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setRoundingMode (RoundingMode.DOWN);
nf.setMaximumFractionDigits(2);
for(PlayerEntity player : eAccess.getWorld().getPlayers()){
Messenger.m(player,"w Pop: ",
"c " + nf.format(chance) + " ",
"^w Chance for the block to be destroyed by the blast: " + chance,
"?" + chance,
"w Remain: ",
String.format("c %.2f ", total),
"^w Chance the block survives the blast: " + total,
"?" + total,
"w Rays: ",
String.format("c %d ", rays),
"^w TNT blast rays going through the block",
"?" + rays,
"w Size: ",
String.format("c %.1f ", eAccess.getPower()),
"^w TNT blast size",
"?" + eAccess.getPower(),
"w @: ",
String.format("c [%.1f %.1f %.1f] ", eAccess.getX(), eAccess.getY(), eAccess.getZ()),
"^w TNT blast location X:" + eAccess.getX() + " Y:" + eAccess.getY() + " Z:" + eAccess.getZ(),
"?" + eAccess.getX() + " " + eAccess.getY() + " " + eAccess.getZ()
);
}
}
public static String formatBigDecimal(BigDecimal x, int decimalPoints) {
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.CEILING);
formatter.setMinimumFractionDigits(decimalPoints);
return formatter.format(x);
}