banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

Mybatis mapping BigDecimal issue

title: "Mybatis Mapping BigDecimal Issue"
date: "2018-11-09"
categories:

  • "source and coding"
    tags:
  • "java"
  • "mybatis"

When mapping database types using numeric and decimal in Mybatis, if you need to use a String for data transfer but the decimal or integer part is very long, Mybatis will map the data as BigDecimal. However, if Mybatis stupidly uses .toString() for conversion, the result may be converted to scientific notation. Today, I encountered this problem with an excessively long order number stored in a certain database. That's enough, I'm going to fix the code.

// MyBatis's approach, directly calling .toString() on BigDecimal
// Printing a floating point number is normal
new BigDecimal("10000000000").toString()
// >>10000000000

// For regular numeric strings, it's fine. We promise that the order number won't exceed the limit, so using a numeric type is fine.
new BigDecimal("100.000").toString()
// >>100.000

// Removing trailing zeros. We use this for order numbers. The order number starts with 123 and then adds zeros.
new BigDecimal("100.000").stripTrailingZeros().toString()
// >>1E+2

// Avoiding scientific notation. This is the correct approach. How can MyBatis not even handle this simple conversion? What else can MyBatis do?
new BigDecimal("100.000").stripTrailingZeros().toPlainString()
// >>100

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.