在Javascript中将十进制数转换为文本字符串分数? [英] Convert decimal amount to text string fraction in Javascript?

查看:117
本文介绍了在Javascript中将十进制数转换为文本字符串分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以数字形式返回的值,可以是十进制数,例如1.15。

I have a value returned as a number, with could be decimal number e.g. "1.15".

但是,我需要将范围中的所有数字格式化为给定的分数。例如,所有大于0但小于.2的数字我想返回1/8。

However, I need to format all numbers in a range to a given fraction. For example, all numbers greater than 0 but less than .2 I want to return "1/8".

我已经开始将此作为一系列if /其他陈述,但我想知道是否有更聪明和更整洁的方式。

I already started to do this as a series of if/else statements, but I was wondering if there was a smarter and neater way.

if (amt > 0 && amt <= .2){
    q = '1/8';
} else if (amt > .2 && amt <= .3){
    q = '1/4';
}  else if (amt > .3 && amt <= .4){
    q = '1/3';
}  else if (amt > .4 && amt <= .5){
    q = '1/2';
} else if (amt > .5 && amt <= .7){
    q = '2/3';
} else if (amt > .7 && amt <= .8){
    q = '3/4';
} else if (amt > .8 && amt <= 1.0){
    q = '7/8';
} else if (amt > 1 && amt <= 1.1){
    q = '1';
} etc.....


推荐答案

将代码移动到一个函数中,您可以从正确的分支返回并跳过所有 else 语句,这些语句可以清除事情非常显着:

Move your code into a function, and you can return from the correct branch and skip all the else statements, which cleans things up pretty dramatically:

function toFraction(amt) {
  if (amt > 0 && amt <= .2) return '1/8';
  if (amt <= .3) return '1/4';
  if (amt <= .4) return '1/3';
  if (amt <= .5) return '1/2';
  // etc
}

这篇关于在Javascript中将十进制数转换为文本字符串分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆