欢迎光临
感受代码之美

Java中BigDecimal和String互转

JAVA.jpg

1.String转BigDecimal

“`

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;

/**
 * @Auther:四个空格-https://www.4spaces.org/
 */
public class DecimalFormatExample {
    public static void main(String[] args) {
        String numStr = "1,000,000,000.999999999999999";
        //Locale in_ID = new Locale("en","US");
        //DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(in_ID);
        DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance();
        nf.setParseBigDecimal(true);

        BigDecimal bd = (BigDecimal) nf.parse(numStr, new ParsePosition(0));

        System.out.println("bd value : " + bd);
    }
}

2.BigDecimal转String

BigDecimal bd = new BigDecimal("10.0001");
System.out.println(bd.toString()); // prints 10.0001
//或者
BigDecimal bd = BigDecimal.valueOf(10.0001);
System.out.println(bd.toString()); // prints 10.0001

注意:new BigDecimal(10.0001),这个构造函数并不能正确表达10.0001这个double类型的数字,它被转换为近似值:10.000099999999999766941982670687139034271240234375

BigDecimal bd = new BigDecimal(10.0001);
System.out.println(bd.toString()); // prints 10.000099999999999766941982670687139034271240234375
转载请注明来源:四个空格 » Java中BigDecimal和String互转

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址