• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
golang中string int float bool类型相互转换

golang中string int float bool类型相互转换

package main

import (
	"fmt"
	"strconv"
)

func IntToString() {
	//todo :int to string
	v := 456
	vS := strconv.Itoa(v)
	fmt.Println(vS) //方法1,简便版

	//todo :int64 to string
	var vI64 int64 = 789
	vInt64S := strconv.FormatInt(vI64, 10) //方法2,int64转string,可指定几进制
	fmt.Println(vInt64S)

	//todo :uint64 to string
	var vUI64 uint64 = 91011
	vUI64S := strconv.FormatUint(vUI64, 10) //方法3, uint64转string,可指定几进制
	fmt.Println(vUI64S)
}

func StringToInt() {
	//todo :string to int/int64
	s := "123"
	vInt, _ := strconv.Atoi(s) //方法1,便捷版
	fmt.Println(vInt)

	vInt64, _ := strconv.ParseInt(s, 10, 64) //方案2,有符号整型,可以指定几进制,整数长度
	fmt.Println(vInt64)

	vUInt64, _ := strconv.ParseUint(s, 10, 64) //方案3,无符号整型,可以指定几进制,整数长度
	fmt.Println(vUInt64)
}

func StringToFloat() {
	//todo :string to float
	f64, _ := strconv.ParseFloat("123.456", 64) //方法1,可以指定长度
	fmt.Println(f64)
}

func FloatToString() {
	//todo :float to string
	f64 := 1223.13252
	sF64 := strconv.FormatFloat(f64, 'f', 5, 64) //方法1,可以指定输出格式、精度、长度
	fmt.Println(sF64)
}

func StringToBool() {
	//todo :string to bool
	 接受 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False 等字符串;
	 其他形式的字符串会返回错误
	b, _ := strconv.ParseBool("1")
	fmt.Println(b)
}
func BoolToString() {
	//todo :bool to string
	sBool := strconv.FormatBool(true) //方法1
	fmt.Println(sBool)
}

func main() {
	StringToInt()
	IntToString()
	StringToFloat()
	FloatToString()
	BoolToString()
	StringToBool()
}
  

  

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/14862205.html

posted on 2021-06-08 11:48  孙龙-程序员  阅读(1884)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3