您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

StringToFloatConverter.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.data.converter;
  17. import java.text.NumberFormat;
  18. import java.util.Locale;
  19. import com.vaadin.data.Result;
  20. import com.vaadin.data.ValueContext;
  21. /**
  22. * A converter that converts from {@link String} to {@link Float} and back. Uses
  23. * the given locale and a {@link NumberFormat} instance for formatting and
  24. * parsing.
  25. * <p>
  26. * Leading and trailing white spaces are ignored when converting from a String.
  27. * <p>
  28. * Override and overwrite {@link #getFormat(Locale)} to use a different format.
  29. *
  30. * @author Vaadin Ltd
  31. * @since 8.0
  32. */
  33. public class StringToFloatConverter
  34. extends AbstractStringToNumberConverter<Float> {
  35. /**
  36. * Creates a new converter instance with the given error message. Empty
  37. * strings are converted to <code>null</code>.
  38. *
  39. * @param errorMessage
  40. * the error message to use if conversion fails
  41. */
  42. public StringToFloatConverter(String errorMessage) {
  43. this(null, errorMessage);
  44. }
  45. /**
  46. * Creates a new converter instance with the given empty string value and
  47. * error message.
  48. *
  49. * @param emptyValue
  50. * the presentation value to return when converting an empty
  51. * string, may be <code>null</code>
  52. * @param errorMessage
  53. * the error message to use if conversion fails
  54. */
  55. public StringToFloatConverter(Float emptyValue, String errorMessage) {
  56. super(emptyValue, errorMessage);
  57. }
  58. @Override
  59. public Result<Float> convertToModel(String value, ValueContext context) {
  60. Result<Number> n = convertToNumber(value,
  61. context.getLocale().orElse(null));
  62. return n.map(number -> {
  63. if (number == null) {
  64. return null;
  65. }
  66. return number.floatValue();
  67. });
  68. }
  69. }