popcorn/Scripts/Extensions/IntExtensions.cs

89 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using System;
using System.Linq;
public static class IntExtensions {
public static int RandomPlusMinus(){
return UnityEngine.Random.Range(0, 2) * 2 - 1;
}
public static int RandomChooseRatio(params int[] ratioArray){
return RandomChooseRatio(new System.Random(), ratioArray);
}
public static int RandomChooseRatio(System.Random rand, params int[] ratioArray){
var totalRatio = ratioArray.Sum();
var value = rand.Next(1, totalRatio + 1);
var result = -1;
for(var i = 0; i < ratioArray.Length; ++i){
if(value <= ratioArray[i]){
result = i;
break;
}
value -= ratioArray[i];
}
return result;
}
public static int PickUp(this int value, int i){
switch(i){
case 0:
return 0;
case 1:
return value % 10;
default:
return (value / (int)Math.Pow(10, i - 1)) % 10;
}
}
public static string ToStringWithDigitCommas(this int value){
return string.Format("{0:#,0}", value);
}
public static string ToTimeString(this int value){
int minute = value / 60;
int second = value % 60;
return string.Format ("{0:D2}:{1:D2}", minute, second);
}
/// 負数未対応
public static string ToChineseNumerals(this int number){
return ((long)number).ToChineseNumerals();
}
public static string ToChineseNumerals(this long number){
if(number < 0) return number.ToString();
if(number == 0) return "";
string[] digit = new string[] { "", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
string[] subUnit = new string[] { "", "十", "百", "千" };
string[] unit = new string[] { "", "万", "億", "兆", "京" };
string str = "";
int keta = 0;
while(number > 0){
int k = keta % 4;
int n = (int)(number % 10);
if(k == 0 && number % 10000 > 0){
str = unit[keta / 4] + str;
}
if(k != 0 && n == 1){
str = subUnit[k] + str;
}else if(n != 0){
str = digit[n] + subUnit[k] + str;
}
++keta;
number /= 10;
}
return str;
}
public static string ToMetricPrefix(this ulong value, int decimalPoint = 1){
string str = string.Format("{0:#,0}", value);
if(str.Length < 4) return str;
string result = str.Substring(0, str.IndexOf(',') + 2).Replace(',', '.');
string[] unit = new string[] { "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
result = string.Format("{0}{1}", result, unit[Mathf.Min(str.Count(c => c == ','), unit.Length - 1)]);
return result;
}
}