本文,將介紹如何使用頁面組件Thymeleaf對貨幣進行自動轉換html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.3.0.RELEASE</version> </dependency>
在resources/templates/下建立頁面currencies.htmljava
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Currency Format</title> </head> <body> <h3 th:text="${#numbers.formatCurrency(param.amount)}"></h3> </body> </html>
建立CurrencyController.javaweb
package com.deepincoding.currencyformat; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class CurrencyController { @GetMapping("/currency") public String current(@RequestParam(value = "amount") String amount){ return "currency"; } }
咱們須要根據瀏覽器的區域來轉換貨幣。使用Accept-Language表示用戶的區域.在Chrome瀏覽器裏能夠設置。 spring
啓動應用後,在瀏覽器裏輸入 http://localhost:8080/currency?amount=1000000.01數組
返回的結果是:¥1,000,000.01瀏覽器
若是把瀏覽的語言設置爲English (United States)app
返回的結果是: $1,000,000.01spring-boot
咱們也能夠轉換一個列表或數組.修改Controller以下:spa
package com.deepincoding.currencyformat; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class CurrencyController { @GetMapping("/currency") public String current(@RequestParam(value = "amount") String amount, @RequestParam(value = "amountList") List amountList){ return "currency"; } }
修改頁面以下:code
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Currency Format</title> </head> <body> <h3 th:text="${#numbers.formatCurrency(param.amount)}"></h3> <h3 th:text="${#numbers.listFormatCurrency(param.amountList)}"></h3> </body> </html>
在瀏覽器裏輸入:http://localhost:8080/currency?amount=1000000.01&amountList=10&amountList=10000&amountList=100000
返回的結果是:¥1,000,000.01 [¥10.00, ¥10,000.00, ¥100,000.00]
尾數是.00,能夠使用strings.replace方法刪除:
<h3 th:text="${#strings.replace(#numbers.formatCurrency(param.amount), '.00', '')}"> </h3>
根據不一樣的區域,小數點的格式可能不一樣。所以,若是咱們想用逗號「,」代替小數點「.」,能夠使用Numbers類提供的 formatDecimal方法:
<h3 th:text="${#numbers.formatDecimal(param.amountList, 1, 2, 'COMMA')}"></h3> <h3 th:text="${#numbers.listFormatDecimal(param.amountList, 1, 2, 'COMMA')}"></h3>