Spring Boot表单提交double值报错:String转Long失败求助
Hey there, let's break down why you're hitting this error and get it sorted out quickly!
The Root Cause
First, let's unpack that error message you're seeing:
Failed to convert from type [java.lang.String] to type [java.lang.Long] for value '2.1'; nested exception is java.lang.NumberFormatException: For input string: "2.1"
This tells us exactly what's going wrong: your Grade model has a field of type Long (which only holds whole numbers), but you're submitting a decimal value like 2.1 as a string from your form. Spring MVC tries to convert that string to a Long and fails because Long can't handle decimal points. When you input an integer, it works because that string can be directly converted to a Long without issues.
Solutions Based on Your Business Needs
1. If You Need to Store Decimal Values (Like 2.1)
If your grades are supposed to have decimal points, you'll need to adjust your model and database to support this:
- Update your
Grademodel: Change the field type fromLongtoDoubleor (even better)BigDecimal(useBigDecimalif you need precise calculations, like for academic grades).// Before private Long score; // After (for basic decimal support) private Double score; // Or for precision (recommended for grades/scores) private BigDecimal score; - Update your database table: Make sure the corresponding column is a decimal type (e.g.,
DOUBLEorDECIMALin MySQL) instead ofBIGINT. - Handle
BigDecimalbinding (if using it): Add the@NumberFormatannotation to your controller parameter to ensure proper conversion:public String submitGradeForm(@ModelAttribute Grade grade, @NumberFormat(pattern = "#.##") BigDecimal score) { // Save to database logic gradeRepository.save(grade); return "success"; }
2. If You Only Allow Integer Grades But Want to Tolerate Decimal Inputs
If your business rules require whole numbers, but you want to handle users accidentally entering decimals (by rounding or truncating), you can add conversion logic in your controller or use a custom converter:
- Controller-side conversion:
@PostMapping("/submit-grade") public String handleGradeSubmission(@RequestParam String scoreInput, Model model) { try { // Convert the input string to a Double first, then to Long Double scoreDouble = Double.parseDouble(scoreInput); // Use longValue() to truncate decimals, or Math.round() to round to nearest integer Long scoreLong = scoreDouble.longValue(); Grade grade = new Grade(); grade.setScore(scoreLong); gradeRepository.save(grade); return "success-page"; } catch (NumberFormatException e) { // Handle invalid input (e.g., non-numeric strings) model.addAttribute("error", "Please enter a valid number"); return "grade-form"; } } - Custom Spring Converter: Create a reusable converter to auto-handle this conversion across your app:
Spring will automatically detect and use this converter whenever it needs to turn a string into a@Component public class StringToLongConverter implements Converter<String, Long> { @Override public Long convert(String source) { if (source == null || source.isBlank()) { return null; } // Convert to Double first, then round/truncate to Long Double value = Double.parseDouble(source); return Math.round(value); // Use longValue() if you want to truncate instead of round } }Long.
3. Frontend Input Validation (Prevent Errors Early)
Add frontend checks to stop invalid inputs before they reach your backend:
- Use HTML5 input type validation:
<!-- Allow decimal grades --> <input type="number" name="score" step="0.1" placeholder="Enter grade (e.g., 2.1)" /> <!-- Restrict to only integers --> <input type="number" name="score" step="1" placeholder="Enter whole number grade" /> - Add JavaScript validation to show real-time feedback if the user enters an invalid format.
Final Notes
The core issue here is a type mismatch between your input (decimal string) and the expected field type (Long). Pick the solution that aligns with your actual business requirements—whether that's supporting decimals, converting inputs to integers, or blocking invalid entries upfront.
内容的提问来源于stack exchange,提问作者Ashley

