java中的%nf_Java中的双十进制格式

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow:

double number = 2354548.235;

Using NumberFormat:

NumberFormat formatter = new DecimalFormat("#0.00");

System.out.println(formatter.format(number));

Using String.format:

System.out.println(String.format("%,.2f", number));

Using DecimalFormat and pattern:

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);

DecimalFormat decimalFormatter = (DecimalFormat) nf;

decimalFormatter.applyPattern("#,###,###.##");

String fString = decimalFormatter.format(number);

System.out.println(fString);

Using DecimalFormat and pattern

DecimalFormat decimalFormat = new DecimalFormat("############.##");

BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));

System.out.println(formattedOutput);

In all cases the output will be:

2354548.23

Note:

During rounding you can add RoundingMode in your formatter. Here are some rounding mode given bellow:

decimalFormat.setRoundingMode(RoundingMode.CEILING);

decimalFormat.setRoundingMode(RoundingMode.FLOOR);

decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);

decimalFormat.setRoundingMode(RoundingMode.HALF_UP);

decimalFormat.setRoundingMode(RoundingMode.UP);

Here are the imports:

import java.math.BigDecimal;

import java.math.RoundingMode;

import java.text.DecimalFormat;

import java.text.NumberFormat;

import java.util.Locale;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值