github.com/sacloud/iaas-api-go@v1.12.0/types/string_number.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package types
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"strconv"
    21  )
    22  
    23  // StringNumber 数値型を文字列で表す型
    24  type StringNumber float64
    25  
    26  // MarshalJSON implements json.Marshaler
    27  func (n *StringNumber) MarshalJSON() ([]byte, error) {
    28  	if n == nil {
    29  		return []byte(`""`), nil
    30  	}
    31  	return []byte(fmt.Sprintf(`"%s"`, n.String())), nil
    32  }
    33  
    34  // UnmarshalJSON implements json.Unmarshaler
    35  func (n *StringNumber) UnmarshalJSON(b []byte) error {
    36  	if string(b) == `""` {
    37  		*n = StringNumber(0)
    38  		return nil
    39  	}
    40  
    41  	var num json.Number
    42  	if err := json.Unmarshal(b, &num); err != nil {
    43  		return err
    44  	}
    45  	number, err := num.Float64()
    46  	if err != nil {
    47  		return err
    48  	}
    49  	*n = StringNumber(number)
    50  	return nil
    51  }
    52  
    53  // String returns the literal text of the number.
    54  func (n StringNumber) String() string {
    55  	if n.Int64() == 0 {
    56  		return ""
    57  	}
    58  	return strconv.FormatFloat(n.Float64(), 'f', -1, 64)
    59  }
    60  
    61  // Int returns the number as an int.
    62  func (n StringNumber) Int() int {
    63  	return int(n)
    64  }
    65  
    66  // Int64 returns the number as an int64.
    67  func (n StringNumber) Int64() int64 {
    68  	return int64(n)
    69  }
    70  
    71  // Float64 returns the number as an float64.
    72  func (n StringNumber) Float64() float64 {
    73  	return float64(n)
    74  }
    75  
    76  // ParseStringNumber 文字列からStringNumberへの変換
    77  func ParseStringNumber(s string) (StringNumber, error) {
    78  	n, err := strconv.ParseInt(s, 10, 64)
    79  	if err != nil {
    80  		return StringNumber(0), err
    81  	}
    82  	return StringNumber(n), nil
    83  }