集册 Java实例教程 格式化和解析数字

格式化和解析数字

欢马劈雪     最近更新时间:2020-01-02 10:19:05

475
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
格式化和解析数字

import java.text.DecimalFormat;

import java.text.ParsePosition;

/** 
 来自 时代Java公众号**/

public class Main {

  private static DecimalFormat formatter = new DecimalFormat();

  public static void main (String[] args){

    formatNumber("##.##", 12.456);

    formatNumber("##.##", 12.456);

    formatNumber("0000.0000", 123.456);

    formatNumber("#.##", -123.456);


    // Positive and negative number format

    formatNumber("#.##;(#.##)", -123.345); 


    // Parse a string to decimal number

    String str = "XY4,123.123";

    String pattern = "#,###.###";

    formatter.applyPattern(pattern);


    // Create a ParsePosition object to specify the first digit of 

    // number in string. It is 4 in "XY4,123.983" and its index is 2./*NowJava.com - 时  代  Java 提 供*/

    ParsePosition pp = new ParsePosition(2);


    Number numberObject = formatter.parse(str, pp);


    double value = numberObject.doubleValue();

    System.out.println("Parsed Value is " + value);

  }


  public static void formatNumber(String pattern, double value) {

      // Apply the pattern

      formatter.applyPattern ( pattern );

展开阅读全文