Servlet 3.1 国际化 - 区域设置 - 百分比

Servlet 可以使用 java.text.NumberFormat 类及其静态方法 getPercentInstance() 来格式化特定于区域设置的百分比

cn/twle/demo/PercentageLocaleServlet.java

// author: 简单教程(www.twle.cn)
// Copyright © 2015-2065 www.twle.cn. All rights reserved.

package cn.twle.demo;

import java.io.*;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;

@WebServlet(name = "PercentageLocaleServlet", 
    urlPatterns = {"percentage_locale"}, loadOnStartup = 1) 
public class PercentageLocaleServlet extends HttpServlet
{

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    // 获取客户端的区域设置
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getPercentInstance(locale);
    String formattedPerc = nft.format(0.51);

    String title = "特定于区域设置的百分比 -  - Servlet 基础教程 | 简单教程(www.twle.cn)";
    String docType = "<!DOCTYPE html>";
      out.println(docType +
      "<title>" + title + "</title>" +
      "<p>"  + title + "</p>" + 
      "<p>" + formattedPerc + "</p>");
  }
}

在浏览器上输入 http://localhost:8080/servlet/percentage_locale 显示结果如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.