2

For Spring JPA within Spring Boot:

Within an @Entity class:

An attribute will hold a percentage value with two digit precision (like: 1.45 %, -195.12 %)

What is the least errorprone way to specify/model this?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29

1 Answers1

4

As chrylis already commented you should use BigDecimal as type. Further you can use the precision and scale attribute of the @Column annotation to define the percentage value.

@Column(precision = 5, scale = 4)
private BigDecimal percentage;

In this case the percentage value is represented by a number between 0 and 1 with a fraction of 4 digits. 1.45% would be then stored as 0.0145. If you want to store the value as 1.45 you can use @Column(precision = 5, scale = 2) But of course this also depends on your datatype. For MS SQL e.g. this would be equivalent to decimal(5,4) (see here).

You find more information in this post as well as within this page.

Alternatively you can also use the Hibernate Validation using the @Digits annotation as described here.

Alex
  • 141
  • 1
  • 10