1/* 2 * Copyright 2015, Rene Gollent, rene@gollent.com. 3 * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de. 4 * Distributed under the terms of the MIT License. 5 */ 6#include "FloatValueFormatter.h" 7 8#include <new> 9 10#include <ctype.h> 11#include <stdio.h> 12#include <stdlib.h> 13 14#include "FloatValue.h" 15 16 17FloatValueFormatter::FloatValueFormatter() 18 : 19 ValueFormatter() 20{ 21} 22 23 24FloatValueFormatter::~FloatValueFormatter() 25{ 26} 27 28 29status_t 30FloatValueFormatter::FormatValue(Value* _value, BString& _output) 31{ 32 FloatValue* value = dynamic_cast<FloatValue*>(_value); 33 if (value == NULL) 34 return B_BAD_VALUE; 35 36 char buffer[64]; 37 BVariant variantValue = value->GetValue(); 38 switch (variantValue.Type()) { 39 case B_FLOAT_TYPE: 40 { 41 snprintf(buffer, sizeof(buffer), "%f", variantValue.ToFloat()); 42 break; 43 } 44 case B_DOUBLE_TYPE: 45 { 46 snprintf(buffer, sizeof(buffer), "%g", variantValue.ToDouble()); 47 break; 48 } 49 } 50 51 _output.SetTo(buffer); 52 53 return B_OK; 54} 55 56 57bool 58FloatValueFormatter::SupportsValidation() const 59{ 60 return true; 61} 62 63 64bool 65FloatValueFormatter::ValidateFormattedValue(const BString& input, 66 type_code type) const 67{ 68 ::Value* value = NULL; 69 return _PerformValidation(input, type, value, false) == B_OK; 70} 71 72 73status_t 74FloatValueFormatter::GetValueFromFormattedInput(const BString& input, 75 type_code type, Value*& _output) const 76{ 77 return _PerformValidation(input, type, _output, true); 78} 79 80 81status_t 82FloatValueFormatter::_PerformValidation(const BString& input, type_code type, 83 ::Value*& _output, bool wantsValue) const 84{ 85 const char* text = input.String(); 86 char *parseEnd = NULL; 87 double parsedValue = strtod(text, &parseEnd); 88 if (parseEnd - text < input.Length() && !isspace(*parseEnd)) 89 return B_NO_MEMORY; 90 91 BVariant newValue; 92 switch (type) { 93 case B_FLOAT_TYPE: 94 { 95 newValue.SetTo((float)parsedValue); 96 break; 97 } 98 case B_DOUBLE_TYPE: 99 { 100 newValue.SetTo(parsedValue); 101 break; 102 } 103 default: 104 return B_BAD_VALUE; 105 } 106 if (wantsValue) { 107 _output = new(std::nothrow) FloatValue(newValue); 108 if (_output == NULL) 109 return B_NO_MEMORY; 110 } 111 112 return B_OK; 113} 114